redis.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/job/main/figure/model"
  7. "go-common/library/log"
  8. "github.com/pkg/errors"
  9. )
  10. const (
  11. _keyWaitDealUser = "w:u" // b_batch_no wait block
  12. _figureKey = "f:%d"
  13. )
  14. func figureKey(mid int64) string {
  15. return fmt.Sprintf(_figureKey, mid)
  16. }
  17. // keyWaitBlock return block cache key.
  18. func keyWaitBlock(version int64, mid int64) string {
  19. return fmt.Sprintf("%s%d%d", _keyWaitDealUser, version, mid%10000)
  20. }
  21. // SetWaiteUserCache set waite deal user cache.
  22. func (d *Dao) SetWaiteUserCache(c context.Context, mid int64, ver int64) (err error) {
  23. if mid <= 0 {
  24. log.Error("%+v", errors.Errorf("SetWaiteUserCache mid [%d] ver [%d] error", mid, ver))
  25. return
  26. }
  27. var (
  28. key = keyWaitBlock(ver, mid)
  29. conn = d.redis.Get(c)
  30. )
  31. defer conn.Close()
  32. if err = conn.Send("SADD", key, mid); err != nil {
  33. log.Error("conn.Send error(%v)", err)
  34. return
  35. }
  36. if err = conn.Send("EXPIRE", key, d.waiteMidExpire); err != nil {
  37. log.Error("conn.Send error(%v)", err)
  38. return
  39. }
  40. if err = conn.Flush(); err != nil {
  41. log.Error("conn.Flush error(%v)", err)
  42. return
  43. }
  44. for i := 0; i < 2; i++ {
  45. if _, err = conn.Receive(); err != nil {
  46. log.Error("conn.Receive error(%v)", err)
  47. return
  48. }
  49. }
  50. return
  51. }
  52. // AddFigureInfoCache put figure to redis
  53. func (d *Dao) AddFigureInfoCache(c context.Context, f *model.Figure) (err error) {
  54. key := figureKey(f.Mid)
  55. conn := d.redis.Get(c)
  56. defer conn.Close()
  57. values, err := json.Marshal(f)
  58. if err != nil {
  59. return
  60. }
  61. if err = conn.Send("SET", key, values); err != nil {
  62. log.Error("conn.Send(SET, %s, %d) error(%v)", key, values, err)
  63. return
  64. }
  65. if err = conn.Send("EXPIRE", key, d.redisExpire); err != nil {
  66. log.Error("conn.Send(Expire, %s, %d) error(%v)", key, d.redisExpire, err)
  67. return
  68. }
  69. return
  70. }
  71. // PingRedis check redis connection
  72. func (d *Dao) PingRedis(c context.Context) (err error) {
  73. conn := d.redis.Get(c)
  74. _, err = conn.Do("SET", "PING", "PONG")
  75. conn.Close()
  76. return
  77. }