gitee.com/lh-her-team/common@v1.5.1/concurrentlru/concurrentlru.go (about)

     1  package concurrentlru
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/golang/groupcache/lru"
     7  )
     8  
     9  type Cache struct {
    10  	mu    sync.Mutex
    11  	cache *lru.Cache
    12  }
    13  
    14  func New(maxEntries int) *Cache {
    15  	var cache Cache
    16  	cache.cache = lru.New(maxEntries)
    17  	return &cache
    18  }
    19  
    20  // Add adds a value to the cache.
    21  func (c *Cache) Add(key lru.Key, value interface{}) {
    22  	c.mu.Lock()
    23  	defer c.mu.Unlock()
    24  	c.cache.Add(key, value)
    25  }
    26  
    27  // Get looks up a key's value from the cache.
    28  func (c *Cache) Get(key lru.Key) (value interface{}, ok bool) {
    29  	c.mu.Lock()
    30  	defer c.mu.Unlock()
    31  	return c.cache.Get(key)
    32  }
    33  
    34  // Remove removes the provided key from the cache.
    35  func (c *Cache) Remove(key lru.Key) {
    36  	c.mu.Lock()
    37  	defer c.mu.Unlock()
    38  	c.cache.Remove(key)
    39  }
    40  
    41  // RemoveOldest removes the oldest item from the cache.
    42  func (c *Cache) RemoveOldest() {
    43  	c.mu.Lock()
    44  	defer c.mu.Unlock()
    45  	c.cache.RemoveOldest()
    46  }
    47  
    48  // Len returns the number of items in the cache.
    49  func (c *Cache) Len() int {
    50  	return c.cache.Len()
    51  }
    52  
    53  // Clear purges all stored items from the cache.
    54  func (c *Cache) Clear() {
    55  	c.mu.Lock()
    56  	defer c.mu.Unlock()
    57  	c.cache.Clear()
    58  }