account_cache.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package account
  2. import (
  3. "context"
  4. "sync"
  5. "time"
  6. account "go-common/app/service/main/account/model"
  7. "go-common/library/log"
  8. )
  9. var (
  10. infoCache = make(map[int64]*account.Info)
  11. nextClearCacheTime time.Time
  12. lock = sync.Mutex{}
  13. )
  14. const (
  15. cacheClearInterval = 60 * time.Minute
  16. )
  17. //GetCachedInfos get cache info
  18. func (d *Dao) GetCachedInfos(c context.Context, mids []int64, ip string) (infos map[int64]*account.Info, err error) {
  19. d.checkClearCache()
  20. var needFindMids []int64
  21. infos = make(map[int64]*account.Info)
  22. lock.Lock()
  23. for _, v := range mids {
  24. var info, ok = infoCache[v]
  25. if !ok {
  26. needFindMids = append(needFindMids, v)
  27. continue
  28. }
  29. log.Info("hit cache! mid=%d", v)
  30. infos[v] = info
  31. }
  32. lock.Unlock()
  33. if len(needFindMids) == 0 {
  34. return
  35. }
  36. var findinfo, e = d.Infos(c, needFindMids, ip)
  37. err = e
  38. if e != nil {
  39. log.Error("try get uid info fail, err=%v", e)
  40. return
  41. }
  42. lock.Lock()
  43. for k, v := range findinfo {
  44. infos[k] = v
  45. infoCache[k] = v
  46. }
  47. lock.Unlock()
  48. return
  49. }
  50. func (d *Dao) checkClearCache() {
  51. var now = time.Now()
  52. if now.Before(nextClearCacheTime) {
  53. return
  54. }
  55. d.clearCache()
  56. }
  57. func (d *Dao) clearCache() {
  58. nextClearCacheTime = time.Now().Add(cacheClearInterval)
  59. if len(infoCache) == 0 {
  60. return
  61. }
  62. lock.Lock()
  63. infoCache = make(map[int64]*account.Info)
  64. lock.Unlock()
  65. }