redis.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package archive
  2. import (
  3. "context"
  4. "fmt"
  5. "go-common/library/cache/redis"
  6. "go-common/library/log"
  7. )
  8. const (
  9. _videoJamTime = "va_v_jam_time"
  10. _editlock = "edit_lock_aid_%d"
  11. )
  12. func lockKey(aid int64) string {
  13. return fmt.Sprintf(_editlock, aid)
  14. }
  15. // GetVideoJam get video traffic jam time
  16. func (d *Dao) GetVideoJam(c context.Context) (seconds int, err error) {
  17. var conn = d.redis.Get(c)
  18. defer conn.Close()
  19. if seconds, err = redis.Int(conn.Do("GET", _videoJamTime)); err != nil {
  20. log.Error("conn.Do(GET,%s) error(%v)", _videoJamTime, err)
  21. }
  22. return
  23. }
  24. //SetNXLock redis lock.
  25. func (d *Dao) SetNXLock(c context.Context, aid int64, times int64) (res bool, err error) {
  26. var (
  27. key = lockKey(aid)
  28. conn = d.redis.Get(c)
  29. )
  30. defer conn.Close()
  31. if res, err = redis.Bool(conn.Do("SETNX", key, "1")); err != nil {
  32. if err == redis.ErrNil {
  33. err = nil
  34. } else {
  35. res = true
  36. log.Error("conn.Do(SETNX(%s)) error(%v)", key, err)
  37. return
  38. }
  39. }
  40. if res {
  41. if _, err = redis.Bool(conn.Do("EXPIRE", key, times)); err != nil {
  42. log.Error("conn.Do(EXPIRE, %s, %d) error(%v)", key, times, err)
  43. return
  44. }
  45. }
  46. return
  47. }
  48. //DelLock del lock.
  49. func (d *Dao) DelLock(c context.Context, aid int64) (err error) {
  50. var (
  51. key = lockKey(aid)
  52. conn = d.redis.Get(c)
  53. )
  54. defer conn.Close()
  55. if _, err = conn.Do("DEL", key); err != nil {
  56. log.Error("conn.Do(del,%v) err(%v)", key, err)
  57. }
  58. return
  59. }