redis.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/job/main/figure-timer/model"
  7. "go-common/library/cache/redis"
  8. "go-common/library/log"
  9. "github.com/pkg/errors"
  10. )
  11. func keyFigure(mid int64) string {
  12. return fmt.Sprintf("f:%d", mid)
  13. }
  14. func keyPendingMids(ver int64, shard int64) string {
  15. return fmt.Sprintf("w:u%d%d", ver, shard)
  16. }
  17. // PingRedis check redis connection
  18. func (d *Dao) PingRedis(c context.Context) (err error) {
  19. conn := d.redis.Get(c)
  20. defer conn.Close()
  21. _, err = conn.Do("SET", "PING", "PONG")
  22. return
  23. }
  24. // FigureCache get FigureUser from cache
  25. func (d *Dao) FigureCache(c context.Context, mid int64) (figure *model.Figure, err error) {
  26. key := keyFigure(mid)
  27. conn := d.redis.Get(c)
  28. defer conn.Close()
  29. item, err := redis.Bytes(conn.Do("GET", key))
  30. if err != nil {
  31. if err == redis.ErrNil {
  32. err = nil
  33. }
  34. return
  35. }
  36. figure = &model.Figure{}
  37. if err = json.Unmarshal(item, &figure); err != nil {
  38. log.Error("json.Unmarshal(%v) err(%v)", item, err)
  39. }
  40. return
  41. }
  42. // SetFigureCache set FigureUser to cache
  43. func (d *Dao) SetFigureCache(c context.Context, figure *model.Figure) (err error) {
  44. key := keyFigure(figure.Mid)
  45. conn := d.redis.Get(c)
  46. defer conn.Close()
  47. values, err := json.Marshal(figure)
  48. if err != nil {
  49. return
  50. }
  51. if err = conn.Send("SET", key, values); err != nil {
  52. log.Error("conn.Send(SET, %s, %v) error(%v)", key, values, err)
  53. return
  54. }
  55. if err = conn.Send("EXPIRE", key, d.redisExpire); err != nil {
  56. log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisExpire, err)
  57. return
  58. }
  59. return
  60. }
  61. // PendingMidsCache get PendingUser set from cache
  62. func (d *Dao) PendingMidsCache(c context.Context, version int64, shard int64) (mids []int64, err error) {
  63. var (
  64. conn = d.redis.Get(c)
  65. key = keyPendingMids(version, shard)
  66. )
  67. defer conn.Close()
  68. if mids, err = redis.Int64s(conn.Do("SMEMBERS", key)); err != nil {
  69. if err == redis.ErrNil {
  70. err = nil
  71. return
  72. }
  73. err = errors.Wrapf(err, "redis.Int64s(conn.Do(SMEMEBERS,%s))", key)
  74. return
  75. }
  76. return
  77. }
  78. // RemoveCache remove figure cache
  79. func (d *Dao) RemoveCache(c context.Context, mid int64) (err error) {
  80. key := keyFigure(mid)
  81. conn := d.redis.Get(c)
  82. defer conn.Close()
  83. if err = conn.Send("DEL", key); err != nil {
  84. log.Error("conn.Send(DEL, %s) error(%v)", key, err)
  85. return
  86. }
  87. return
  88. }