redis.go 849 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package newcomer
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/log"
  6. )
  7. const (
  8. _preLock = "creative_task_"
  9. )
  10. func lockKey(key string) string {
  11. return fmt.Sprintf("%s%s", _preLock, key)
  12. }
  13. //Lock .
  14. func (d *Dao) Lock(ctx context.Context, key string, ttl int) (gotLock bool, err error) {
  15. var lockValue = "1"
  16. conn := d.redis.Get(ctx)
  17. defer conn.Close()
  18. realKey := lockKey(key)
  19. var res interface{}
  20. //ttl 毫秒(PX) NX 其实就是 SetNX功能
  21. res, err = conn.Do("SET", realKey, lockValue, "PX", ttl, "NX")
  22. if err != nil {
  23. log.Error("receive_lock failed:%s:%s", realKey, err.Error())
  24. return
  25. }
  26. if res != nil {
  27. gotLock = true
  28. }
  29. return
  30. }
  31. //UnLock .
  32. func (d *Dao) UnLock(ctx context.Context, key string) (err error) {
  33. realKey := lockKey(key)
  34. conn := d.redis.Get(ctx)
  35. defer conn.Close()
  36. _, err = conn.Do("DEL", realKey)
  37. return
  38. }