redis.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package black
  2. import (
  3. "context"
  4. "strconv"
  5. "go-common/library/cache/redis"
  6. "github.com/pkg/errors"
  7. )
  8. const (
  9. _prefixBlack = "b_"
  10. )
  11. // keyBlack is.
  12. func keyBlack(mid int64) string {
  13. return _prefixBlack + strconv.FormatInt(mid, 10)
  14. }
  15. func (d *Dao) blackCache(c context.Context, mid int64) (aidm map[int64]struct{}, err error) {
  16. var aids []int64
  17. conn := d.redis.Get(c)
  18. key := keyBlack(mid)
  19. defer conn.Close()
  20. if aids, err = redis.Int64s(conn.Do("ZREVRANGE", key, 0, -1)); err != nil {
  21. err = errors.Wrapf(err, "conn.Do(ZREVRANGE,%s,0,-1)", key)
  22. return
  23. }
  24. aidm = make(map[int64]struct{}, len(aids))
  25. for _, aid := range aids {
  26. aidm[aid] = struct{}{}
  27. }
  28. return
  29. }
  30. // addBlackCache is.
  31. func (d *Dao) addBlackCache(c context.Context, mid int64, aids ...int64) (err error) {
  32. if len(aids) == 0 {
  33. return
  34. }
  35. key := keyBlack(mid)
  36. conn := d.redis.Get(c)
  37. defer conn.Close()
  38. for _, aid := range aids {
  39. if err = conn.Send("ZADD", key, aid, aid); err != nil {
  40. err = errors.Wrapf(err, "conn.Send(ZADD,%s,%d,%d)", key, aid, aid)
  41. return
  42. }
  43. }
  44. if err = conn.Send("EXPIRE", key, d.expireRds); err != nil {
  45. err = errors.Wrapf(err, "conn.Send(EXPIRE,%s,%d)", key, d.expireRds)
  46. return
  47. }
  48. if err = conn.Flush(); err != nil {
  49. return
  50. }
  51. for i := 0; i < len(aids)+1; i++ {
  52. if _, err = conn.Receive(); err != nil {
  53. return
  54. }
  55. }
  56. return
  57. }
  58. // delBlackCache is.
  59. func (d *Dao) delBlackCache(c context.Context, mid, aid int64) (err error) {
  60. key := keyBlack(mid)
  61. conn := d.redis.Get(c)
  62. defer conn.Close()
  63. if _, err = conn.Do("ZREM", key, aid); err != nil {
  64. err = errors.Wrapf(err, "conn.Do(ZREM,%s,%d)", key, aid)
  65. }
  66. return
  67. }
  68. // expireBlackCache is.
  69. func (d *Dao) expireBlackCache(c context.Context, mid int64) (ok bool, err error) {
  70. key := keyBlack(mid)
  71. conn := d.redis.Get(c)
  72. defer conn.Close()
  73. if ok, err = redis.Bool(conn.Do("EXPIRE", key, d.expireRds)); err != nil {
  74. err = errors.Wrapf(err, "conn.Do(EXPIRE,%s,%d)", key, d.expireRds)
  75. }
  76. return
  77. }