icon_redis.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. resmdl "go-common/app/service/main/resource/model"
  6. "go-common/library/cache/redis"
  7. "go-common/library/log"
  8. )
  9. const (
  10. _indexIconKey = "iik"
  11. _indexIconBakKey = "b_iik"
  12. )
  13. // SetIndexIconCache set index icon cache and bak cache
  14. func (d *Dao) SetIndexIconCache(c context.Context, data []*resmdl.IndexIcon) (err error) {
  15. key := _indexIconKey
  16. conn := d.redis.Get(c)
  17. defer conn.Close()
  18. if err = d.setIndexIconCache(conn, key, d.redisRcExpire, data); err != nil {
  19. return
  20. }
  21. key = _indexIconBakKey
  22. connBak := d.redisBak.Get(c)
  23. err = d.setIndexIconCache(connBak, key, d.redisRcBakExpire, data)
  24. connBak.Close()
  25. return
  26. }
  27. func (d *Dao) setIndexIconCache(conn redis.Conn, key string, expire int32, data []*resmdl.IndexIcon) (err error) {
  28. var bs []byte
  29. if bs, err = json.Marshal(data); err != nil {
  30. log.Error("json.Marshal(%v) error (%v)", data, err)
  31. return
  32. }
  33. if err = conn.Send("SET", key, bs); err != nil {
  34. log.Error("conn.Send(SET, %s, %s) error(%v)", key, string(bs), err)
  35. return
  36. }
  37. if err = conn.Send("EXPIRE", key, expire); err != nil {
  38. log.Error("conn.Send(Expire, %s, %d) error(%v)", key, expire, err)
  39. return
  40. }
  41. if err = conn.Flush(); err != nil {
  42. log.Error("conn.Flush error(%v)", err)
  43. return
  44. }
  45. for i := 0; i < 2; i++ {
  46. if _, err = conn.Receive(); err != nil {
  47. log.Error("conn.Receive() error(%v)", err)
  48. return
  49. }
  50. }
  51. return
  52. }
  53. // IndexIconCache get index icon cache
  54. func (d *Dao) IndexIconCache(c context.Context) (res []*resmdl.IndexIcon, err error) {
  55. key := _indexIconKey
  56. conn := d.redis.Get(c)
  57. defer conn.Close()
  58. res, err = d.indexIconCache(conn, key)
  59. return
  60. }
  61. // IndexIconBakCache get index icon bak cache
  62. func (d *Dao) IndexIconBakCache(c context.Context) (res []*resmdl.IndexIcon, err error) {
  63. d.cacheProm.Incr("indexicon_remote_cache")
  64. key := _indexIconBakKey
  65. conn := d.redisBak.Get(c)
  66. defer conn.Close()
  67. res, err = d.indexIconCache(conn, key)
  68. return
  69. }
  70. func (d *Dao) indexIconCache(conn redis.Conn, key string) (res []*resmdl.IndexIcon, err error) {
  71. var value []byte
  72. if value, err = redis.Bytes(conn.Do("GET", key)); err != nil {
  73. if err == redis.ErrNil {
  74. err = nil
  75. } else {
  76. log.Error("conn.Do(GET, %s) error(%v)", key, err)
  77. }
  78. return
  79. }
  80. if err = json.Unmarshal(value, &res); err != nil {
  81. log.Error("json.Unmarshal(%v) error(%v)", value, err)
  82. }
  83. return
  84. }