local.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package cache
  2. import (
  3. "sync"
  4. "time"
  5. "go-common/app/service/bbq/recsys-recall/conf"
  6. )
  7. // Solt .
  8. type Solt struct {
  9. data []byte
  10. ctime int64
  11. maxAge int64
  12. lastUsed int64
  13. keepAlived int64
  14. }
  15. // LocalCache .
  16. type LocalCache struct {
  17. d map[string]*Solt
  18. l1tags map[string]byte
  19. l2tags map[string]byte
  20. c *conf.LocalCacheConfig
  21. lock *sync.RWMutex
  22. }
  23. // NewLocalCache .
  24. func NewLocalCache(c *conf.LocalCacheConfig) *LocalCache {
  25. l1 := make(map[string]byte)
  26. l2 := make(map[string]byte)
  27. for _, v := range c.L1Tags {
  28. l1[v] = byte(1)
  29. }
  30. for _, v := range c.L2Tags {
  31. l2[v] = byte(1)
  32. }
  33. return &LocalCache{
  34. d: make(map[string]*Solt),
  35. l1tags: l1,
  36. l2tags: l2,
  37. c: c,
  38. lock: &sync.RWMutex{},
  39. }
  40. }
  41. // Set .
  42. func (lc *LocalCache) Set(key string, val []byte) bool {
  43. lc.lock.Lock()
  44. defer lc.lock.Unlock()
  45. keep := lc.c.Level3
  46. if _, ok := lc.l1tags[key]; ok {
  47. keep = lc.c.Level1
  48. } else if _, ok := lc.l2tags[key]; ok {
  49. keep = lc.c.Level2
  50. }
  51. lc.d[key] = &Solt{
  52. data: val,
  53. ctime: time.Now().Unix(),
  54. maxAge: int64(lc.c.MaxAge),
  55. lastUsed: time.Now().Unix(),
  56. keepAlived: int64(keep),
  57. }
  58. return true
  59. }
  60. // Get .
  61. func (lc *LocalCache) Get(key string) []byte {
  62. lc.lock.RLock()
  63. defer lc.lock.RUnlock()
  64. current := time.Now().Unix()
  65. s := lc.d[key]
  66. if s == nil {
  67. return nil
  68. }
  69. keepAlived := s.keepAlived / int64(time.Second)
  70. maxAge := s.maxAge / int64(time.Second)
  71. if keepAlived < (current-s.lastUsed) || maxAge < (current-s.ctime) {
  72. return nil
  73. }
  74. s.lastUsed = current
  75. return s.data
  76. }