redis.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package dao
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "time"
  7. "go-common/library/cache/redis"
  8. )
  9. const (
  10. _expShard = 10000
  11. _expAddedPrefix = "ea_%s_%d_%d"
  12. _expire = 86400
  13. )
  14. func expAddedKey(tp string, mid int64, day int) string {
  15. return fmt.Sprintf(_expAddedPrefix, tp, day, mid/_expShard)
  16. }
  17. func leader() (key string, value string) {
  18. value, _ = os.Hostname()
  19. key = fmt.Sprintf("member-job:leader:%d", time.Now().Day())
  20. return key, value
  21. }
  22. // SetExpAdded set user exp added of tp,
  23. func (d *Dao) SetExpAdded(c context.Context, mid int64, day int, tp string) (b bool, err error) {
  24. conn := d.redis.Get(c)
  25. defer conn.Close()
  26. if err = conn.Send("SETBIT", expAddedKey(tp, mid, day), mid%_expShard, 1); err != nil {
  27. return
  28. }
  29. if err = conn.Send("EXPIRE", expAddedKey(tp, mid, day), _expire); err != nil {
  30. return
  31. }
  32. if err = conn.Flush(); err != nil {
  33. return
  34. }
  35. if b, err = redis.Bool(conn.Receive()); err != nil {
  36. return
  37. }
  38. conn.Receive()
  39. return
  40. }
  41. // ExpAdded check if user had add exp.
  42. func (d *Dao) ExpAdded(c context.Context, mid int64, day int, tp string) (b bool, err error) {
  43. conn := d.redis.Get(c)
  44. b, err = redis.Bool(conn.Do("GETBIT", expAddedKey(tp, mid, day), mid%_expShard))
  45. conn.Close()
  46. return
  47. }
  48. // LeaderEleciton eleciton job leader.
  49. func (d *Dao) LeaderEleciton(c context.Context) (elected bool) {
  50. key, value := leader()
  51. conn := d.redis.Get(c)
  52. elected, _ = redis.Bool(conn.Do("SETNX", key, value))
  53. if elected {
  54. conn.Do("EXPIRE", key, 600)
  55. }
  56. conn.Close()
  57. return
  58. }