WrapWithLRUCache wraps a given `Cache` c with a LRU cache. The LRU cache will always store items in both caches. However it will only fetch items from the underlying cache if the LRU cache doesn't have the item. Items fetched from the underlying cache will be stored in the LRU cache with a default T
(c Cache, name string, reg prometheus.Registerer, lruSize int, defaultTTL time.Duration, logger log.Logger)
| 40 | // The LRU cache is limited in number of items using `lruSize`. This means this cache is not tailored for large items or items that have a big |
| 41 | // variation in size. |
| 42 | func WrapWithLRUCache(c Cache, name string, reg prometheus.Registerer, lruSize int, defaultTTL time.Duration, logger log.Logger) (*LRUCache, error) { |
| 43 | l, err := lru.NewLRU[string, *Item](lruSize, nil) |
| 44 | if err != nil { |
| 45 | return nil, err |
| 46 | } |
| 47 | |
| 48 | cache := &LRUCache{ |
| 49 | c: c, |
| 50 | logger: logger, |
| 51 | lru: l, |
| 52 | name: name, |
| 53 | defaultTTL: defaultTTL, |
| 54 | |
| 55 | requests: promauto.With(reg).NewCounter(prometheus.CounterOpts{ |
| 56 | Name: "cache_memory_requests_total", |
| 57 | Help: "Total number of requests to the in-memory cache.", |
| 58 | ConstLabels: map[string]string{"name": name}, |
| 59 | }), |
| 60 | hits: promauto.With(reg).NewCounter(prometheus.CounterOpts{ |
| 61 | Name: "cache_memory_hits_total", |
| 62 | Help: "Total number of requests to the in-memory cache that were a hit.", |
| 63 | ConstLabels: map[string]string{"name": name}, |
| 64 | }), |
| 65 | } |
| 66 | |
| 67 | cache.items = promauto.With(reg).NewGaugeFunc(prometheus.GaugeOpts{ |
| 68 | Name: "cache_memory_items_count", |
| 69 | Help: "Total number of items currently in the in-memory cache.", |
| 70 | ConstLabels: map[string]string{"name": name}, |
| 71 | }, func() float64 { |
| 72 | cache.mtx.Lock() |
| 73 | defer cache.mtx.Unlock() |
| 74 | |
| 75 | return float64(cache.lru.Len()) |
| 76 | }) |
| 77 | |
| 78 | return cache, nil |
| 79 | } |
| 80 | |
| 81 | func (l *LRUCache) SetAsync(key string, value []byte, ttl time.Duration) { |
| 82 | l.c.SetAsync(key, value, ttl) |