redis.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/interface/main/up-rating/model"
  7. "go-common/library/cache/redis"
  8. "github.com/pkg/errors"
  9. )
  10. // GetUpRatingCache ...
  11. func (d *Dao) GetUpRatingCache(c context.Context, mid int64) (rating *model.Rating, err error) {
  12. var (
  13. key = upRatingKey(mid)
  14. conn = d.redis.Get(c)
  15. data []byte
  16. )
  17. defer conn.Close()
  18. if data, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  19. if err == redis.ErrNil {
  20. err = nil
  21. }
  22. return
  23. }
  24. rating = new(model.Rating)
  25. if err = json.Unmarshal(data, &rating); err != nil {
  26. err = errors.WithStack(err)
  27. return nil, err
  28. }
  29. return
  30. }
  31. // ExpireUpRatingCache ...
  32. func (d *Dao) ExpireUpRatingCache(c context.Context, mid int64) (err error) {
  33. var (
  34. key = upRatingKey(mid)
  35. conn = d.redis.Get(c)
  36. )
  37. defer conn.Close()
  38. if err = conn.Send("EXPIRE", key, 0); err != nil {
  39. return
  40. }
  41. return
  42. }
  43. // SetUpRatingCache ...
  44. func (d *Dao) SetUpRatingCache(c context.Context, mid int64, rating *model.Rating) (err error) {
  45. var (
  46. key = upRatingKey(mid)
  47. conn = d.redis.Get(c)
  48. bs []byte
  49. )
  50. defer conn.Close()
  51. if bs, err = json.Marshal(rating); err != nil {
  52. return errors.WithStack(err)
  53. }
  54. if err = conn.Send("SET", key, bs); err != nil {
  55. return
  56. }
  57. if err = conn.Send("EXPIRE", key, d.upRatingExpire); err != nil {
  58. return
  59. }
  60. if err = conn.Flush(); err != nil {
  61. return
  62. }
  63. if _, err = conn.Receive(); err != nil {
  64. return
  65. }
  66. return
  67. }
  68. func upRatingKey(mid int64) string {
  69. return fmt.Sprintf("up_rating_detail_mid_%d", mid)
  70. }