cache.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package collection
  2. import (
  3. "container/list"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/wuntsong-org/go-zero-plus/core/logx"
  8. "github.com/wuntsong-org/go-zero-plus/core/mathx"
  9. "github.com/wuntsong-org/go-zero-plus/core/syncx"
  10. )
  11. const (
  12. defaultCacheName = "proc"
  13. slots = 300
  14. statInterval = time.Minute
  15. // make the expiry unstable to avoid lots of cached items expire at the same time
  16. // make the unstable expiry to be [0.95, 1.05] * seconds
  17. expiryDeviation = 0.05
  18. )
  19. var emptyLruCache = emptyLru{}
  20. type (
  21. // CacheOption defines the method to customize a Cache.
  22. CacheOption func(cache *Cache)
  23. // A Cache object is an in-memory cache.
  24. Cache struct {
  25. name string
  26. lock sync.Mutex
  27. data map[string]any
  28. expire time.Duration
  29. timingWheel *TimingWheel
  30. lruCache lru
  31. barrier syncx.SingleFlight
  32. unstableExpiry mathx.Unstable
  33. stats *cacheStat
  34. }
  35. )
  36. // NewCache returns a Cache with given expire.
  37. func NewCache(expire time.Duration, opts ...CacheOption) (*Cache, error) {
  38. cache := &Cache{
  39. data: make(map[string]any),
  40. expire: expire,
  41. lruCache: emptyLruCache,
  42. barrier: syncx.NewSingleFlight(),
  43. unstableExpiry: mathx.NewUnstable(expiryDeviation),
  44. }
  45. for _, opt := range opts {
  46. opt(cache)
  47. }
  48. if len(cache.name) == 0 {
  49. cache.name = defaultCacheName
  50. }
  51. cache.stats = newCacheStat(cache.name, cache.size)
  52. timingWheel, err := NewTimingWheel(time.Second, slots, func(k, v any) {
  53. key, ok := k.(string)
  54. if !ok {
  55. return
  56. }
  57. cache.Del(key)
  58. })
  59. if err != nil {
  60. return nil, err
  61. }
  62. cache.timingWheel = timingWheel
  63. return cache, nil
  64. }
  65. // Del deletes the item with the given key from c.
  66. func (c *Cache) Del(key string) {
  67. c.lock.Lock()
  68. delete(c.data, key)
  69. c.lruCache.remove(key)
  70. c.lock.Unlock()
  71. c.timingWheel.RemoveTimer(key)
  72. }
  73. // Get returns the item with the given key from c.
  74. func (c *Cache) Get(key string) (any, bool) {
  75. value, ok := c.doGet(key)
  76. if ok {
  77. c.stats.IncrementHit()
  78. } else {
  79. c.stats.IncrementMiss()
  80. }
  81. return value, ok
  82. }
  83. // Set sets value into c with key.
  84. func (c *Cache) Set(key string, value any) {
  85. c.SetWithExpire(key, value, c.expire)
  86. }
  87. // SetWithExpire sets value into c with key and expire with the given value.
  88. func (c *Cache) SetWithExpire(key string, value any, expire time.Duration) {
  89. c.lock.Lock()
  90. _, ok := c.data[key]
  91. c.data[key] = value
  92. c.lruCache.add(key)
  93. c.lock.Unlock()
  94. expiry := c.unstableExpiry.AroundDuration(expire)
  95. if ok {
  96. c.timingWheel.MoveTimer(key, expiry)
  97. } else {
  98. c.timingWheel.SetTimer(key, value, expiry)
  99. }
  100. }
  101. // Take returns the item with the given key.
  102. // If the item is in c, return it directly.
  103. // If not, use fetch method to get the item, set into c and return it.
  104. func (c *Cache) Take(key string, fetch func() (any, error)) (any, error) {
  105. if val, ok := c.doGet(key); ok {
  106. c.stats.IncrementHit()
  107. return val, nil
  108. }
  109. var fresh bool
  110. val, err := c.barrier.Do(key, func() (any, error) {
  111. // because O(1) on map search in memory, and fetch is an IO query
  112. // so we do double check, cache might be taken by another call
  113. if val, ok := c.doGet(key); ok {
  114. return val, nil
  115. }
  116. v, e := fetch()
  117. if e != nil {
  118. return nil, e
  119. }
  120. fresh = true
  121. c.Set(key, v)
  122. return v, nil
  123. })
  124. if err != nil {
  125. return nil, err
  126. }
  127. if fresh {
  128. c.stats.IncrementMiss()
  129. return val, nil
  130. }
  131. // got the result from previous ongoing query
  132. c.stats.IncrementHit()
  133. return val, nil
  134. }
  135. func (c *Cache) doGet(key string) (any, bool) {
  136. c.lock.Lock()
  137. defer c.lock.Unlock()
  138. value, ok := c.data[key]
  139. if ok {
  140. c.lruCache.add(key)
  141. }
  142. return value, ok
  143. }
  144. func (c *Cache) onEvict(key string) {
  145. // already locked
  146. delete(c.data, key)
  147. c.timingWheel.RemoveTimer(key)
  148. }
  149. func (c *Cache) size() int {
  150. c.lock.Lock()
  151. defer c.lock.Unlock()
  152. return len(c.data)
  153. }
  154. // WithLimit customizes a Cache with items up to limit.
  155. func WithLimit(limit int) CacheOption {
  156. return func(cache *Cache) {
  157. if limit > 0 {
  158. cache.lruCache = newKeyLru(limit, cache.onEvict)
  159. }
  160. }
  161. }
  162. // WithName customizes a Cache with the given name.
  163. func WithName(name string) CacheOption {
  164. return func(cache *Cache) {
  165. cache.name = name
  166. }
  167. }
  168. type (
  169. lru interface {
  170. add(key string)
  171. remove(key string)
  172. }
  173. emptyLru struct{}
  174. keyLru struct {
  175. limit int
  176. evicts *list.List
  177. elements map[string]*list.Element
  178. onEvict func(key string)
  179. }
  180. )
  181. func (elru emptyLru) add(string) {
  182. }
  183. func (elru emptyLru) remove(string) {
  184. }
  185. func newKeyLru(limit int, onEvict func(key string)) *keyLru {
  186. return &keyLru{
  187. limit: limit,
  188. evicts: list.New(),
  189. elements: make(map[string]*list.Element),
  190. onEvict: onEvict,
  191. }
  192. }
  193. func (klru *keyLru) add(key string) {
  194. if elem, ok := klru.elements[key]; ok {
  195. klru.evicts.MoveToFront(elem)
  196. return
  197. }
  198. // Add new item
  199. elem := klru.evicts.PushFront(key)
  200. klru.elements[key] = elem
  201. // Verify size not exceeded
  202. if klru.evicts.Len() > klru.limit {
  203. klru.removeOldest()
  204. }
  205. }
  206. func (klru *keyLru) remove(key string) {
  207. if elem, ok := klru.elements[key]; ok {
  208. klru.removeElement(elem)
  209. }
  210. }
  211. func (klru *keyLru) removeOldest() {
  212. elem := klru.evicts.Back()
  213. if elem != nil {
  214. klru.removeElement(elem)
  215. }
  216. }
  217. func (klru *keyLru) removeElement(e *list.Element) {
  218. klru.evicts.Remove(e)
  219. key := e.Value.(string)
  220. delete(klru.elements, key)
  221. klru.onEvict(key)
  222. }
  223. type cacheStat struct {
  224. name string
  225. hit uint64
  226. miss uint64
  227. sizeCallback func() int
  228. }
  229. func newCacheStat(name string, sizeCallback func() int) *cacheStat {
  230. st := &cacheStat{
  231. name: name,
  232. sizeCallback: sizeCallback,
  233. }
  234. go st.statLoop()
  235. return st
  236. }
  237. func (cs *cacheStat) IncrementHit() {
  238. atomic.AddUint64(&cs.hit, 1)
  239. }
  240. func (cs *cacheStat) IncrementMiss() {
  241. atomic.AddUint64(&cs.miss, 1)
  242. }
  243. func (cs *cacheStat) statLoop() {
  244. ticker := time.NewTicker(statInterval)
  245. defer ticker.Stop()
  246. for range ticker.C {
  247. hit := atomic.SwapUint64(&cs.hit, 0)
  248. miss := atomic.SwapUint64(&cs.miss, 0)
  249. total := hit + miss
  250. if total == 0 {
  251. continue
  252. }
  253. percent := 100 * float32(hit) / float32(total)
  254. logx.Statf("cache(%s) - qpm: %d, hit_ratio: %.1f%%, elements: %d, hit: %d, miss: %d",
  255. cs.name, total, percent, cs.sizeCallback(), hit, miss)
  256. }
  257. }