Documentation ¶
Index ¶
- Constants
- Variables
- func MatchPattern(pattern, s string) bool
- type Cache
- func (cache *Cache) Clear()
- func (cache *Cache) Count() int
- func (cache *Cache) Delete(key string) bool
- func (cache *Cache) DeleteAll(keys []string) int
- func (cache *Cache) DeleteKeysByPattern(pattern string) int
- func (cache *Cache) EvictionPolicy() EvictionPolicy
- func (cache *Cache) Expire(key string, ttl time.Duration) bool
- func (cache *Cache) Get(key string) (any, bool)
- func (cache *Cache) GetAll() map[string]any
- func (cache *Cache) GetByKeys(keys []string) map[string]any
- func (cache *Cache) GetKeysByPattern(pattern string, limit int) []string
- func (cache *Cache) GetValue(key string) any
- func (cache *Cache) MaxMemoryUsage() int
- func (cache *Cache) MaxSize() int
- func (cache *Cache) MemoryUsage() int
- func (cache *Cache) Set(key string, value any)
- func (cache *Cache) SetAll(entries map[string]any)
- func (cache *Cache) SetAllWithTTL(entries map[string]any, ttl time.Duration)
- func (cache *Cache) SetWithTTL(key string, value any, ttl time.Duration)
- func (cache *Cache) StartJanitor() error
- func (cache *Cache) Stats() Statistics
- func (cache *Cache) StopJanitor()
- func (cache *Cache) TTL(key string) (time.Duration, error)
- func (cache *Cache) WithDefaultTTL(ttl time.Duration) *Cache
- func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache
- func (cache *Cache) WithForceNilInterfaceOnNilPointer(forceNilInterfaceOnNilPointer bool) *Cache
- func (cache *Cache) WithMaxMemoryUsage(maxMemoryUsageInBytes int) *Cache
- func (cache *Cache) WithMaxSize(maxSize int) *Cache
- type Entry
- type EvictionPolicy
- type Statistics
Constants ¶
const ( // NoMaxSize means that the cache has no maximum number of entries in the cache // Setting Cache.maxSize to this value also means there will be no eviction NoMaxSize = 0 // NoMaxMemoryUsage means that the cache has no maximum number of entries in the cache NoMaxMemoryUsage = 0 // DefaultMaxSize is the max size set if no max size is specified DefaultMaxSize = 100000 // NoExpiration is the value that must be used as TTL to specify that the given key should never expire NoExpiration = -1 Kilobyte = 1024 Megabyte = 1024 * Kilobyte Gigabyte = 1024 * Megabyte )
const ( // JanitorShiftTarget is the target number of expired keys to find during passive clean up duty // before pausing the passive expired keys eviction process JanitorShiftTarget = 25 // JanitorMaxIterationsPerShift is the maximum number of nodes to traverse before pausing // // This is to prevent the janitor from traversing the entire cache, which could take a long time // to complete depending on the size of the cache. // // By limiting it to a small number, we are effectively reducing the impact of passive eviction. JanitorMaxIterationsPerShift = 1000 // JanitorMinShiftBackOff is the minimum interval between each iteration of steps // defined by JanitorMaxIterationsPerShift JanitorMinShiftBackOff = 50 * time.Millisecond // JanitorMaxShiftBackOff is the maximum interval between each iteration of steps // defined by JanitorMaxIterationsPerShift JanitorMaxShiftBackOff = 500 * time.Millisecond )
Variables ¶
var ( ErrKeyDoesNotExist = errors.New("key does not exist") // Returned when a cache key does not exist ErrKeyHasNoExpiration = errors.New("key has no expiration") // Returned when a cache key has no expiration ErrJanitorAlreadyRunning = errors.New("janitor is already running") // Returned when the janitor has already been started )
var (
Debug = false
)
Functions ¶
func MatchPattern ¶
MatchPattern checks whether a string matches a pattern
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache is the core struct of gocache which contains the data as well as all relevant configuration fields
Do not instantiate this struct directly, use NewCache instead
func NewCache ¶
func NewCache() *Cache
NewCache creates a new Cache
Should be used in conjunction with Cache.WithMaxSize, Cache.WithMaxMemoryUsage and/or Cache.WithEvictionPolicy
gocache.NewCache().WithMaxSize(10000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
func (*Cache) Count ¶
Count returns the total amount of entries in the cache, regardless of whether they're expired or not
func (*Cache) DeleteAll ¶
DeleteAll deletes multiple entries based on the keys passed as parameter
Returns the number of keys deleted
func (*Cache) DeleteKeysByPattern ¶ added in v2.1.0
DeleteKeysByPattern deletes all entries matching a given key pattern and returns the number of entries deleted.
Note that DeleteKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
func (*Cache) EvictionPolicy ¶
func (cache *Cache) EvictionPolicy() EvictionPolicy
EvictionPolicy returns the EvictionPolicy of the Cache
func (*Cache) Expire ¶
Expire sets a key's expiration time
A TTL of -1 means that the key will never expire A TTL of 0 means that the key will expire immediately If using LRU, note that this does not reset the position of the key
Returns true if the cache key exists and has had its expiration time altered
func (*Cache) Get ¶
Get retrieves an entry using the key passed as parameter If there is no such entry, the value returned will be nil and the boolean will be false If there is an entry, the value returned will be the value cached and the boolean will be true
func (*Cache) GetAll ¶
GetAll retrieves all cache entries
If the eviction policy is LeastRecentlyUsed, note that unlike Get and GetByKeys, this does not update the last access timestamp. The reason for this is that since all cache entries will be accessed, updating the last access timestamp would provide very little benefit while harming the ability to accurately determine the next key that will be evicted
You should probably avoid using this if you have a lot of entries.
GetKeysByPattern is a good alternative if you want to retrieve entries that you do not have the key for, as it only retrieves the keys and does not trigger active eviction and has a parameter for setting a limit to the number of keys you wish to retrieve.
func (*Cache) GetByKeys ¶
GetByKeys retrieves multiple entries using the keys passed as parameter All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or whether it doesn't exist in the cache using only this function.
func (*Cache) GetKeysByPattern ¶
GetKeysByPattern retrieves a slice of keys that match a given pattern If the limit is set to 0, the entire cache will be searched for matching keys. If the limit is above 0, the search will stop once the specified number of matching keys have been found.
e.g.
cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU). The reason for that behavior is that these two (active eviction and access) only applies when you access the value of the cache entry, and this function only returns the keys.
func (*Cache) GetValue ¶
GetValue retrieves an entry using the key passed as parameter Unlike Get, this function only returns the value
func (*Cache) MaxMemoryUsage ¶
MaxMemoryUsage returns the configured maxMemoryUsage of the cache
func (*Cache) MaxSize ¶
MaxSize returns the maximum amount of keys that can be present in the cache before new entries trigger the eviction of the tail
func (*Cache) MemoryUsage ¶
MemoryUsage returns the current memory usage of the cache's dataset in bytes If MaxMemoryUsage is set to NoMaxMemoryUsage, this will return 0
func (*Cache) SetAllWithTTL ¶ added in v2.2.0
SetAllWithTTL creates or updates multiple values
func (*Cache) SetWithTTL ¶
SetWithTTL creates or updates a key with a given value and sets an expiration time (-1 is NoExpiration)
The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is provided, the entry will not be created if the key doesn't exist
func (*Cache) StartJanitor ¶
StartJanitor starts the janitor on a different goroutine The janitor's job is to delete expired keys in the background, in other words, it takes care of passive eviction. It can be stopped by calling Cache.StopJanitor. If you do not start the janitor, expired keys will only be deleted when they are accessed through Get, GetByKeys, or GetAll.
func (*Cache) Stats ¶
func (cache *Cache) Stats() Statistics
Stats returns statistics from the cache
func (*Cache) TTL ¶
TTL returns the time until the cache entry specified by the key passed as parameter will be deleted.
func (*Cache) WithDefaultTTL ¶ added in v2.2.0
WithDefaultTTL sets the default TTL for each entry (unless a different TTL is specified using SetWithTTL or SetAllWithTTL)
Defaults to NoExpiration (-1)
func (*Cache) WithEvictionPolicy ¶
func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache
WithEvictionPolicy sets eviction algorithm.
Defaults to FirstInFirstOut (FIFO)
func (*Cache) WithForceNilInterfaceOnNilPointer ¶
WithForceNilInterfaceOnNilPointer sets whether all Set-like functions should set a value as nil if the interface passed has a nil value but not a nil type.
In Go, an interface is only nil if both its type and value are nil, which means that a nil pointer (e.g. (*Struct)(nil)) will retain its attribution to the type, and the unmodified value returned from Cache.Get, for instance, would return false when compared with nil if this option is set to false.
We can bypass this by detecting if the interface's value is nil and setting it to nil rather than a nil pointer, which will make the value returned from Cache.Get return true when compared with nil. This is exactly what passing true to WithForceNilInterfaceOnNilPointer does, and it's also the default behavior.
Alternatively, you may pass false to WithForceNilInterfaceOnNilPointer, which will mean that you'll have to cast the value returned from Cache.Get to its original type to check for whether the pointer returned is nil or not.
If set to true (default):
cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(true) cache.Set("key", (*Struct)(nil)) value, _ := cache.Get("key") // the following returns true, because the interface{} (any) was forcefully set to nil if value == nil {} // the following will panic, because the value has been casted to its type (which is nil) if value.(*Struct) == nil {}
If set to false:
cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(false) cache.Set("key", (*Struct)(nil)) value, _ := cache.Get("key") // the following returns false, because the interface{} (any) returned has a non-nil type (*Struct) if value == nil {} // the following returns true, because the value has been cast to its type if value.(*Struct) == nil {}
In other words, if set to true, you do not need to cast the value returned from the cache to check if the value is nil.
Defaults to true
func (*Cache) WithMaxMemoryUsage ¶
WithMaxMemoryUsage sets the maximum amount of memory that can be used by the cache at any given time
NOTE: This is approximate.
Setting this to NoMaxMemoryUsage will disable eviction by memory usage
func (*Cache) WithMaxSize ¶
WithMaxSize sets the maximum amount of entries that can be in the cache at any given time A maxSize of 0 or less means infinite
type Entry ¶
type Entry struct { // Key is the name of the cache entry Key string // Value is the value of the cache entry Value any // RelevantTimestamp is the variable used to store either: // - creation timestamp, if the Cache's EvictionPolicy is FirstInFirstOut // - last access timestamp, if the Cache's EvictionPolicy is LeastRecentlyUsed // // Note that updating an existing entry will also update this value RelevantTimestamp time.Time // Expiration is the unix time in nanoseconds at which the entry will expire (-1 means no expiration) Expiration int64 // contains filtered or unexported fields }
Entry is a cache entry
func (*Entry) Accessed ¶
func (entry *Entry) Accessed()
Accessed updates the Entry's RelevantTimestamp to now
func (*Entry) SizeInBytes ¶
SizeInBytes returns the size of an entry in bytes, approximately.
type EvictionPolicy ¶
type EvictionPolicy string
EvictionPolicy is what dictates how evictions are handled
const ( // LeastRecentlyUsed is an eviction policy that causes the most recently accessed cache entry to be moved to the // head of the cache. Effectively, this causes the cache entries that have not been accessed for some time to // gradually move closer and closer to the tail, and since the tail is the entry that gets deleted when an eviction // is required, it allows less used cache entries to be evicted while keeping recently accessed entries at or close // to the head. // // For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would // put 3 at the head and 1 at the tail: // 3 (head) -> 2 -> 1 (tail) // If the cache entry 1 was then accessed, 1 would become the head and 2 the tail: // 1 (head) -> 3 -> 2 (tail) // If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (2) would then be evicted: // 4 (head) -> 1 -> 3 (tail) LeastRecentlyUsed EvictionPolicy = "LeastRecentlyUsed" // FirstInFirstOut is an eviction policy that causes cache entries to be evicted in the same order that they are // created. // // For instance, creating a Cache with a Cache.MaxSize of 3 and creating the entries 1, 2 and 3 in that order would // put 3 at the head and 1 at the tail: // 3 (head) -> 2 -> 1 (tail) // If the cache entry 1 was then accessed, unlike with LeastRecentlyUsed, nothing would change: // 3 (head) -> 2 -> 1 (tail) // If a cache entry 4 was then created, because the Cache.MaxSize is 3, the tail (1) would then be evicted: // 4 (head) -> 3 -> 2 (tail) FirstInFirstOut EvictionPolicy = "FirstInFirstOut" )
type Statistics ¶
type Statistics struct { // EvictedKeys is the number of keys that were evicted EvictedKeys uint64 // ExpiredKeys is the number of keys that were automatically deleted as a result of expiring ExpiredKeys uint64 // Hits is the number of cache hits Hits uint64 // Misses is the number of cache misses Misses uint64 }