redis.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package dao
  2. import (
  3. "context"
  4. "strconv"
  5. "go-common/library/cache/redis"
  6. "github.com/pkg/errors"
  7. )
  8. const (
  9. _prefixBlackList = "zl_"
  10. )
  11. func keyZlimit(aid int64) (key string) {
  12. key = _prefixBlackList + strconv.FormatInt(aid, 10)
  13. return
  14. }
  15. // ExistsAuth if existes ruls in redis.
  16. func (d *Dao) ExistsAuth(c context.Context, aid int64) (ok bool, err error) {
  17. conn := d.redis.Get(c)
  18. defer conn.Close()
  19. if ok, err = redis.Bool(conn.Do("EXISTS", keyZlimit(aid))); err != nil {
  20. err = errors.Wrapf(err, "EXISTS %s", keyZlimit(aid))
  21. }
  22. return
  23. }
  24. // Auth get zone rule from redis
  25. func (d *Dao) Auth(c context.Context, aid int64, zoneids []int64) (res []int64, err error) {
  26. var playauth int64
  27. key := keyZlimit(aid)
  28. conn := d.redis.Get(c)
  29. defer conn.Close()
  30. for _, v := range zoneids {
  31. if err = conn.Send("HGET", key, v); err != nil {
  32. err = errors.Wrapf(err, "HGET %s %d", key, v)
  33. return
  34. }
  35. }
  36. if err = conn.Flush(); err != nil {
  37. err = errors.WithStack(err)
  38. return
  39. }
  40. for range zoneids {
  41. if playauth, err = redis.Int64(conn.Receive()); err != nil {
  42. if err != redis.ErrNil {
  43. err = errors.WithStack(err)
  44. return
  45. }
  46. err = nil
  47. }
  48. res = append(res, playauth)
  49. }
  50. return
  51. }
  52. // AddAuth add zone rule from redis
  53. func (d *Dao) AddAuth(c context.Context, zoneids map[int64]map[int64]int64) (err error) {
  54. var key string
  55. conn := d.redis.Get(c)
  56. defer conn.Close()
  57. count := 0
  58. for aid, zids := range zoneids {
  59. if key == "" {
  60. key = keyZlimit(aid)
  61. }
  62. for zid, auth := range zids {
  63. if err = conn.Send("HSET", key, zid, auth); err != nil {
  64. err = errors.Wrapf(err, "HGET %s %d", key, zid)
  65. return
  66. }
  67. count++
  68. }
  69. }
  70. if err = conn.Send("EXPIRE", key, d.expire); err != nil {
  71. err = errors.Wrapf(err, "EXPIRE %s %d", key, d.expire)
  72. return
  73. }
  74. if err = conn.Flush(); err != nil {
  75. err = errors.WithStack(err)
  76. return
  77. }
  78. for i := 0; i <= count; i++ {
  79. if _, err = conn.Receive(); err != nil {
  80. err = errors.WithStack(err)
  81. return
  82. }
  83. }
  84. return
  85. }