lock.go 660 B

12345678910111213141516171819202122232425262728293031
  1. package dao
  2. import (
  3. "context"
  4. "go-common/library/cache/redis"
  5. "go-common/library/log"
  6. )
  7. //TryLock ...
  8. func (d *Dao) TryLock(c context.Context, key string, value string, timeout int) (ok bool, err error) {
  9. var conn = d.redis.Get(c)
  10. defer conn.Close()
  11. _, err = redis.String(conn.Do("SET", key, value, "EX", timeout, "NX"))
  12. if err == redis.ErrNil {
  13. log.Info("TryLock redis key(%s) is ErrNil!", key)
  14. return false, nil
  15. }
  16. if err != nil {
  17. return false, err
  18. }
  19. return true, nil
  20. }
  21. // UnLock ...
  22. func (d *Dao) UnLock(c context.Context, key string) (err error) {
  23. var conn = d.redis.Get(c)
  24. defer conn.Close()
  25. _, err = conn.Do("DEL", key)
  26. return
  27. }