Documentation ¶
Overview ¶
Package cache implements LRU (Least Recently Used) cache algorithm.
Cache capacity can be optionally limited by both size in bytes and a number of items. Items can keep track of their modification and access time.
Example:
// Create a 1 MB cache. c := cache.New(cache.Config{ MaxBytes: 1024*1024 }) ... // Query cache and insert item if it's not there. var x someType v, ok := c.Get("key") if !ok { // Item is not in cache, fetch it from main storage... x = ... // ...then add it to cache. c.Set("key", x, x.Size()) } else { x = v.(someType) } // x now contains the value.
Index ¶
- type Cache
- func (c *Cache) Config() Config
- func (c *Cache) Get(key string) (value interface{}, ok bool)
- func (c *Cache) GetBytes(key string) (value []byte, ok bool)
- func (c *Cache) GetItem(key string) (it Item, ok bool)
- func (c *Cache) Items() []Item
- func (c *Cache) Len() int
- func (c *Cache) OldestItem() (it Item, ok bool)
- func (c *Cache) Reconfigure(newConfig Config)
- func (c *Cache) Remove(key string) bool
- func (c *Cache) Reset()
- func (c *Cache) Set(key string, value interface{}, size int64)
- func (c *Cache) SetBytes(key string, value []byte)
- func (c *Cache) Size() int64
- type Config
- type Item
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Cache ¶
func (*Cache) Get ¶
Get returns a value of item cached under the given key. If there is no such key in the cache, it returns nil, false.
func (*Cache) GetBytes ¶
GetBytes is like Get, but returns a bytes slice value. It panics if value is not a byte slice.
func (*Cache) OldestItem ¶
OldestItem returns a copy of least recently used item. If cache contains no items, the second return value is false. Accessing oldest item via this function doesn't change its access time or the order of items in cache.
func (*Cache) Reconfigure ¶
Reconfigure sets a new cache configuration.
func (*Cache) Set ¶
Set sets or updates a cache item for the given key to the given value, and the given value size in bytes.
type Config ¶
type Config struct { // Maximum number of items the cache can contain (unlimited by default). MaxItems int // Maximum byte capacity of cache (unlimited by default). MaxBytes int64 // Track item access time (false by default). TrackAccessTime bool // Item expiration duration. // // An item is removed from cache when trying to get it if the given // time passed since its modification time. // // Set to zero for no expiration (default). Expires time.Duration // Function to call when an item is dropped or removed from cache // (nil by default). // // The handler function is given a copy of the removed item as an argument. // During its execution the cache is locked, and must not be accessed or // modified from the handler function. RemoveHandler func(Item) }