account_redis.go 1.8 KB

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