view_redis.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/interface/main/web/model"
  7. "go-common/library/cache/redis"
  8. "go-common/library/log"
  9. )
  10. const (
  11. _keyArchiveFmt = "va_%d"
  12. )
  13. func keyArchive(aid int64) string {
  14. return fmt.Sprintf(_keyArchiveFmt, aid)
  15. }
  16. // SetViewBakCache set view archive page data to cache.
  17. func (d *Dao) SetViewBakCache(c context.Context, aid int64, a *model.View) (err error) {
  18. key := keyArchive(aid)
  19. conn := d.redisBak.Get(c)
  20. defer conn.Close()
  21. var bs []byte
  22. if bs, err = json.Marshal(a); err != nil {
  23. log.Error("SetViewBakCache json.Marshal(%v) error(%v)", a, err)
  24. return
  25. }
  26. if err = conn.Send("SET", key, bs); err != nil {
  27. log.Error("SetViewBakCache conn.Send(SET,%s,%s) error(%v)", key, string(bs), err)
  28. return
  29. }
  30. if err = conn.Send("EXPIRE", key, d.redisArchiveBakExpire); err != nil {
  31. log.Error("SetViewBakCache conn.Send(EXPIRE,%s,%d) error(%v)", key, d.redisArchiveBakExpire, err)
  32. return
  33. }
  34. if err = conn.Flush(); err != nil {
  35. log.Error("SetViewBakCache conn.Flush error(%v)", err)
  36. return
  37. }
  38. for i := 0; i < 2; i++ {
  39. if _, err = conn.Receive(); err != nil {
  40. log.Error("SetViewBakCache conn.Recevie(%d) error(%v0", i, err)
  41. }
  42. }
  43. return
  44. }
  45. // ViewBakCache get view archive page data from cache.
  46. func (d *Dao) ViewBakCache(c context.Context, aid int64) (rs *model.View, err error) {
  47. key := keyArchive(aid)
  48. conn := d.redisBak.Get(c)
  49. defer conn.Close()
  50. var values []byte
  51. if values, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  52. if err == redis.ErrNil {
  53. err = nil
  54. log.Warn("ViewBakCache redis (%s) return nil ", key)
  55. } else {
  56. log.Error("ViewBakCache conn.Do(GET,%s) error(%v)", key, err)
  57. }
  58. return
  59. }
  60. if err = json.Unmarshal(values, &rs); err != nil {
  61. log.Error("ViewBakCache json.Unmarshal(%v) error(%v)", values, err)
  62. }
  63. return
  64. }