redis.go 1.9 KB

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