cache.go 2.0 KB

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