agecache

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2023 License: MIT Imports: 5 Imported by: 5

README

agecache

Thread-safe LRU cache supporting expiration and jitter. Supports cache statistics, as well as eviction and expiration callbacks. Differs from some implementations in that OnEviction is only invoked when an entry is removed as a result of the LRU eviction policy - not when you explicitly delete it or when it expires. OnExpiration is available and invoked when an item expires. Expiration can be passively enforced when performing a Get, or actively enforced by iterating over all keys with an interval.

cache := agecache.New(agecache.Config{
	Capacity: 100,
	MaxAge:   70 * time.Minute,
	MinAge:   60 * time.Minute,
	OnExpiration: func(key, value interface{}) {
		// Handle expiration
	},
	OnEviction: func(key, value interface{}) {
		// Handle eviction
	},
})

cache.Set("foo", "bar")

Documentation

Full docs are available on Godoc.

Documentation

Overview

Package agecache is largely inspired by https://github.com/golang/groupcache

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache implements a thread-safe fixed-capacity LRU cache.

func New

func New(config Config) *Cache

New constructs an LRU Cache with the given Config object. config.Capacity must be a positive int, and config.MaxAge a zero or positive duration. A duration of zero disables item expiration. Panics given an invalid config.Capacity or config.MaxAge.

func (*Cache) Clear

func (cache *Cache) Clear()

Clear empties the cache.

func (*Cache) EvictOldest

func (cache *Cache) EvictOldest() bool

EvictOldest removes the oldest item from the cache, while also invoking any eviction callback. A bool is returned indicating whether or not an item was removed

func (*Cache) Get

func (cache *Cache) Get(key interface{}) (interface{}, bool)

Get returns the value stored at `key`. The boolean value reports whether or not the value was found. The OnExpiration callback is invoked if the value had expired on access

func (*Cache) Has

func (cache *Cache) Has(key interface{}) bool

Has returns whether or not the `key` is in the cache without updating how recently it was accessed or deleting it for having expired.

func (*Cache) Keys

func (cache *Cache) Keys() []interface{}

Keys returns all keys in the cache.

func (*Cache) Len

func (cache *Cache) Len() int

Len returns the number of items in the cache.

func (*Cache) OnEviction

func (cache *Cache) OnEviction(callback func(key, value interface{}))

OnEviction sets the eviction callback.

func (*Cache) OnExpiration

func (cache *Cache) OnExpiration(callback func(key, value interface{}))

OnExpiration sets the expiration callback.

func (*Cache) OrderedKeys

func (cache *Cache) OrderedKeys() []interface{}

OrderedKeys returns all keys in the cache, ordered from oldest to newest.

func (*Cache) Peek

func (cache *Cache) Peek(key interface{}) (interface{}, bool)

Peek returns the value at the specified key and a boolean specifying whether or not it was found, without updating how recently it was accessed or deleting it for having expired.

func (*Cache) Remove

func (cache *Cache) Remove(key interface{}) bool

Remove removes the provided key from the cache, returning a bool indicating whether or not it existed.

func (*Cache) Resize

func (cache *Cache) Resize(n int) error

Resize the cache to hold at most n entries. If n is smaller than the current size, entries are evicted to fit the new size. It errors if n <= 0.

func (*Cache) Set

func (cache *Cache) Set(key, value interface{}) bool

Set updates a key:value pair in the cache. Returns true if an eviction occurrred, and subsequently invokes the OnEviction callback.

func (*Cache) SetMaxAge

func (cache *Cache) SetMaxAge(maxAge time.Duration) error

SetMaxAge updates the max age for items in the cache. A duration of zero disables expiration. A negative duration, or one that is less than minAge, results in an error.

func (*Cache) SetMinAge

func (cache *Cache) SetMinAge(minAge time.Duration) error

SetMinAge updates the min age for items in the cache. A duration of zero or equal to maxAge disables jitter. A negative duration, or one that is greater than maxAge, results in an error.

func (*Cache) Stats

func (cache *Cache) Stats() Stats

Stats returns cache stats.

type Config

type Config struct {
	// Maximum number of items in the cache
	Capacity int
	// Optional max duration before an item expires. Must be greater than or
	// equal to MinAge. If zero, expiration is disabled.
	MaxAge time.Duration
	// Optional min duration before an item expires. Must be less than or equal
	// to MaxAge. When less than MaxAge, uniformly distributed random jitter is
	// added to the expiration time. If equal or zero, jitter is disabled.
	MinAge time.Duration
	// Type of key expiration: Passive or Active
	ExpirationType ExpirationType
	// For active expiration, how often to iterate over the keyspace. Defaults
	// to the MaxAge
	ExpirationInterval time.Duration
	// Optional callback invoked when an item is evicted due to the LRU policy
	OnEviction func(key, value interface{})
	// Optional callback invoked when an item expired
	OnExpiration func(key, value interface{})
}

Config configures the cache.

type ExpirationType

type ExpirationType int

ExpirationType enumerates expiration types.

const (
	// PassiveExpration expires items passively by checking
	// the item expiry when `.Get()` is called, if the item was
	// expired, it is deleted and nil is returned.
	PassiveExpration ExpirationType = iota

	// ActiveExpiration expires items by managing
	// a goroutine to actively GC expired items in the background.
	ActiveExpiration
)

type RandGenerator

type RandGenerator interface {
	Int63n(n int64) int64
}

RandGenerator represents a random number generator.

type Stats

type Stats struct {
	Capacity  int64 `metric:"capacity" type:"gauge"`    // Gauge, maximum capacity for the cache
	Count     int64 `metric:"count" type:"gauge"`       // Gauge, number of items in the cache
	Sets      int64 `metric:"sets" type:"counter"`      // Counter, number of sets
	Gets      int64 `metric:"gets" type:"counter"`      // Counter, number of gets
	Hits      int64 `metric:"hits" type:"counter"`      // Counter, number of cache hits from Get operations
	Misses    int64 `metric:"misses" type:"counter"`    // Counter, number of cache misses from Get operations
	Evictions int64 `metric:"evictions" type:"counter"` // Counter, number of evictions
}

Stats hold cache statistics.

The struct supports stats package tags, example:

prev := cache.Stats()
s := cache.Stats().Delta(prev)
stats.WithPrefix("mycache").Observe(s)

func (Stats) Delta

func (stats Stats) Delta(previous Stats) Stats

Delta returns a Stats object such that all counters are calculated as the difference since the previous.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL