cache.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package collection
  2. import (
  3. "container/list"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "github.com/tal-tech/go-zero/core/logx"
  8. "github.com/tal-tech/go-zero/core/mathx"
  9. "github.com/tal-tech/go-zero/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 func(cache *Cache)
  22. Cache struct {
  23. name string
  24. lock sync.Mutex
  25. data map[string]interface{}
  26. evicts *list.List
  27. expire time.Duration
  28. timingWheel *TimingWheel
  29. lruCache lru
  30. barrier syncx.SharedCalls
  31. unstableExpiry mathx.Unstable
  32. stats *cacheStat
  33. }
  34. )
  35. func NewCache(expire time.Duration, opts ...CacheOption) (*Cache, error) {
  36. cache := &Cache{
  37. data: make(map[string]interface{}),
  38. expire: expire,
  39. lruCache: emptyLruCache,
  40. barrier: syncx.NewSharedCalls(),
  41. unstableExpiry: mathx.NewUnstable(expiryDeviation),
  42. }
  43. for _, opt := range opts {
  44. opt(cache)
  45. }
  46. if len(cache.name) == 0 {
  47. cache.name = defaultCacheName
  48. }
  49. cache.stats = newCacheStat(cache.name, cache.size)
  50. timingWheel, err := NewTimingWheel(time.Second, slots, func(k, v interface{}) {
  51. key, ok := k.(string)
  52. if !ok {
  53. return
  54. }
  55. cache.Del(key)
  56. })
  57. if err != nil {
  58. return nil, err
  59. }
  60. cache.timingWheel = timingWheel
  61. return cache, nil
  62. }
  63. func (c *Cache) Del(key string) {
  64. c.lock.Lock()
  65. delete(c.data, key)
  66. c.lruCache.remove(key)
  67. c.lock.Unlock()
  68. c.timingWheel.RemoveTimer(key)
  69. }
  70. func (c *Cache) Get(key string) (interface{}, bool) {
  71. c.lock.Lock()
  72. value, ok := c.data[key]
  73. if ok {
  74. c.lruCache.add(key)
  75. }
  76. c.lock.Unlock()
  77. if ok {
  78. c.stats.IncrementHit()
  79. } else {
  80. c.stats.IncrementMiss()
  81. }
  82. return value, ok
  83. }
  84. func (c *Cache) Set(key string, value interface{}) {
  85. c.lock.Lock()
  86. _, ok := c.data[key]
  87. c.data[key] = value
  88. c.lruCache.add(key)
  89. c.lock.Unlock()
  90. expiry := c.unstableExpiry.AroundDuration(c.expire)
  91. if ok {
  92. c.timingWheel.MoveTimer(key, expiry)
  93. } else {
  94. c.timingWheel.SetTimer(key, value, expiry)
  95. }
  96. }
  97. func (c *Cache) Take(key string, fetch func() (interface{}, error)) (interface{}, error) {
  98. val, fresh, err := c.barrier.DoEx(key, func() (interface{}, error) {
  99. v, e := fetch()
  100. if e != nil {
  101. return nil, e
  102. }
  103. c.Set(key, v)
  104. return v, nil
  105. })
  106. if err != nil {
  107. return nil, err
  108. }
  109. if fresh {
  110. c.stats.IncrementMiss()
  111. return val, nil
  112. } else {
  113. // got the result from previous ongoing query
  114. c.stats.IncrementHit()
  115. }
  116. return val, nil
  117. }
  118. func (c *Cache) onEvict(key string) {
  119. // already locked
  120. delete(c.data, key)
  121. c.timingWheel.RemoveTimer(key)
  122. }
  123. func (c *Cache) size() int {
  124. c.lock.Lock()
  125. defer c.lock.Unlock()
  126. return len(c.data)
  127. }
  128. func WithLimit(limit int) CacheOption {
  129. return func(cache *Cache) {
  130. if limit > 0 {
  131. cache.lruCache = newKeyLru(limit, cache.onEvict)
  132. }
  133. }
  134. }
  135. func WithName(name string) CacheOption {
  136. return func(cache *Cache) {
  137. cache.name = name
  138. }
  139. }
  140. type (
  141. lru interface {
  142. add(key string)
  143. remove(key string)
  144. }
  145. emptyLru struct{}
  146. keyLru struct {
  147. limit int
  148. evicts *list.List
  149. elements map[string]*list.Element
  150. onEvict func(key string)
  151. }
  152. )
  153. func (elru emptyLru) add(string) {
  154. }
  155. func (elru emptyLru) remove(string) {
  156. }
  157. func newKeyLru(limit int, onEvict func(key string)) *keyLru {
  158. return &keyLru{
  159. limit: limit,
  160. evicts: list.New(),
  161. elements: make(map[string]*list.Element),
  162. onEvict: onEvict,
  163. }
  164. }
  165. func (klru *keyLru) add(key string) {
  166. if elem, ok := klru.elements[key]; ok {
  167. klru.evicts.MoveToFront(elem)
  168. return
  169. }
  170. // Add new item
  171. elem := klru.evicts.PushFront(key)
  172. klru.elements[key] = elem
  173. // Verify size not exceeded
  174. if klru.evicts.Len() > klru.limit {
  175. klru.removeOldest()
  176. }
  177. }
  178. func (klru *keyLru) remove(key string) {
  179. if elem, ok := klru.elements[key]; ok {
  180. klru.removeElement(elem)
  181. }
  182. }
  183. func (klru *keyLru) removeOldest() {
  184. elem := klru.evicts.Back()
  185. if elem != nil {
  186. klru.removeElement(elem)
  187. }
  188. }
  189. func (klru *keyLru) removeElement(e *list.Element) {
  190. klru.evicts.Remove(e)
  191. key := e.Value.(string)
  192. delete(klru.elements, key)
  193. klru.onEvict(key)
  194. }
  195. type cacheStat struct {
  196. name string
  197. hit uint64
  198. miss uint64
  199. sizeCallback func() int
  200. }
  201. func newCacheStat(name string, sizeCallback func() int) *cacheStat {
  202. st := &cacheStat{
  203. name: name,
  204. sizeCallback: sizeCallback,
  205. }
  206. go st.statLoop()
  207. return st
  208. }
  209. func (cs *cacheStat) IncrementHit() {
  210. atomic.AddUint64(&cs.hit, 1)
  211. }
  212. func (cs *cacheStat) IncrementMiss() {
  213. atomic.AddUint64(&cs.miss, 1)
  214. }
  215. func (cs *cacheStat) statLoop() {
  216. ticker := time.NewTicker(statInterval)
  217. defer ticker.Stop()
  218. for {
  219. select {
  220. case <-ticker.C:
  221. hit := atomic.SwapUint64(&cs.hit, 0)
  222. miss := atomic.SwapUint64(&cs.miss, 0)
  223. total := hit + miss
  224. if total == 0 {
  225. continue
  226. }
  227. percent := 100 * float32(hit) / float32(total)
  228. logx.Statf("cache(%s) - qpm: %d, hit_ratio: %.1f%%, elements: %d, hit: %d, miss: %d",
  229. cs.name, total, percent, cs.sizeCallback(), hit, miss)
  230. }
  231. }
  232. }