user_conf_cache.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "go-common/app/interface/main/kvo/model"
  7. mc "go-common/library/cache/memcache"
  8. "go-common/library/log"
  9. )
  10. const (
  11. _userConfKeyPrefix = "u"
  12. )
  13. func cacheUserConfKey(mid int64, moduleKey int) string {
  14. return fmt.Sprintf("%v_%v_%v", _userConfKeyPrefix, mid, moduleKey)
  15. }
  16. // UserConfCache user config cache
  17. func (d *Dao) UserConfCache(ctx context.Context, mid int64, moduleKey int) (uc *model.UserConf, err error) {
  18. var r *mc.Item
  19. conn := d.cache.Get(ctx)
  20. defer conn.Close()
  21. if r, err = conn.Get(cacheUserConfKey(mid, moduleKey)); err != nil {
  22. if err == mc.ErrNotFound {
  23. err = nil
  24. return
  25. }
  26. log.Error("conn.Get(%s) error(%v)", cacheUserConfKey(mid, moduleKey), err)
  27. return
  28. }
  29. if err = json.Unmarshal(r.Value, &uc); err != nil {
  30. log.Error("json.Unmarshal(%s) error(%v)", r.Value, err)
  31. uc = nil
  32. }
  33. return
  34. }
  35. // SetUserConfCache set user config cache
  36. func (d *Dao) SetUserConfCache(ctx context.Context, uc *model.UserConf) (err error) {
  37. bs, err := json.Marshal(uc)
  38. if err != nil {
  39. log.Error("SetUserConfCache.Marshal err:%v", err)
  40. return
  41. }
  42. conn := d.cache.Get(ctx)
  43. defer conn.Close()
  44. if err = conn.Set(&mc.Item{
  45. Key: cacheUserConfKey(uc.Mid, uc.ModuleKey),
  46. Value: bs,
  47. Expiration: d.mcExpire,
  48. }); err != nil {
  49. log.Error("dao.SetUserConfCache(%v,%v) err:%v", cacheUserConfKey(uc.Mid, uc.ModuleKey), bs, err)
  50. return
  51. }
  52. return
  53. }
  54. // DelUserConfCache del user config cache
  55. func (d *Dao) DelUserConfCache(ctx context.Context, mid int64, moduleKey int) (err error) {
  56. conn := d.cache.Get(ctx)
  57. defer conn.Close()
  58. if err = conn.Delete(cacheUserConfKey(mid, moduleKey)); err == mc.ErrNotFound {
  59. err = nil
  60. }
  61. return
  62. }