Documentation
¶
Overview ¶
Package lru implements a generic Least Recently Used (LRU) cache with support for "spam" items and TTL (Time-To-Live). The cache maintains a maximum number of items, evicting the least recently used item when the limit is reached. Items can be added, retrieved, and deleted from the cache. Regular items are moved to the front of the cache when accessed or updated, while "spam" items maintain their position. Items can expire based on their TTL settings. This allows for preferential treatment of non-spam items in terms of retention, while still caching spam items. The cache is safe for concurrent use.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
type Cache[K comparable, V any] struct { // contains filtered or unexported fields }
Cache is a generic LRU cache that supports "spam" items and TTL. Caches should be created by calling NewCache or NewCacheWithTTL.
func NewCache ¶
func NewCache[K comparable, V any](maxItems int) *Cache[K, V]
NewCache creates a new LRU cache with the specified maximum number of items.
func NewCacheWithTTL ¶
NewCacheWithTTL creates a new LRU cache with the specified maximum number of items and default TTL duration. When you are done with the cache, you should call Close to stop the background cleanup goroutine.
func (*Cache[K, V]) CleanupExpired ¶
func (c *Cache[K, V]) CleanupExpired()
CleanupExpired removes all expired items from the cache.
func (*Cache[K, V]) Close ¶
func (c *Cache[K, V]) Close()
Close stops the background cleanup goroutine if it's running. It should be called when the cache is no longer needed to prevent resource leaks.
func (*Cache[K, V]) Delete ¶
func (c *Cache[K, V]) Delete(key K)
Delete removes an item from the cache if it exists.
func (*Cache[K, V]) Get ¶
Get retrieves an item from the cache, moving non-spam items to the front. It returns the value and a boolean indicating whether the key was found. If the item has expired, it will be removed and not returned.
func (*Cache[K, V]) Set ¶
Set adds or updates an item in the cache, evicting the LRU item if necessary. The isSpam parameter determines whether the item should be treated as spam. If the item is spam, it will not be moved to the front of the cache. Uses the default TTL if one was specified when creating the cache.