ttlcache

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2023 License: MIT Imports: 5 Imported by: 0

README

TTLCache - an in-memory cache with expiration

Original Project

TTLCache was forked from github.com/ReneKroon/ttlcache

extra

  1. provide feasibility between Get and LoaderFunction by providing KeyProvider interface
type KeyProvider interface {
	GetKey() string
}

// examples...
localLoader := func(key KeyProvider) (data interface{}, ttl time.Duration, err error) {
return "local", 0, nil
}

key, _ := cache.Get(NewSimpleKey("test"))
  1. fix metrics Retrievals and Hits

Documentation

Index

Constants

View Source
const (
	// ErrClosed is raised when operating on a cache where Close() has already been called.
	ErrClosed = constError("cache already closed")
	// ErrNotFound indicates that the requested key is not present in the cache
	ErrNotFound = constError("key not found")
)
View Source
const (
	// ItemNotExpire Will avoid the item being expired by TTL, but can still be exired by callback etc.
	ItemNotExpire time.Duration = -1
	// ItemExpireWithGlobalTTL will use the global TTL when set.
	ItemExpireWithGlobalTTL time.Duration = 0
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache is a synchronized map of items that can auto-expire once stale

func NewCache

func NewCache() *Cache

NewCache is a helper to create instance of the Cache struct

func (*Cache) Close

func (cache *Cache) Close() error

Close calls Purge after stopping the goroutine that does ttl checking, for a clean shutdown. The cache is no longer cleaning up after the first call to Close, repeated calls are safe and return ErrClosed.

func (*Cache) Count

func (cache *Cache) Count() int

Count returns the number of items in the cache. Returns zero when the cache has been closed.

func (*Cache) Get

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

Get is a thread-safe way to lookup items Every lookup, also touches the item, hence extending its life

func (*Cache) GetByLoader

func (cache *Cache) GetByLoader(key KeyProvider, customLoaderFunction LoaderFunction) (interface{}, error)

GetByLoader can take a per key loader function (i.e. to propagate context)

func (*Cache) GetByLoaderWithTtl

func (cache *Cache) GetByLoaderWithTtl(key KeyProvider, customLoaderFunction LoaderFunction) (interface{}, time.Duration, error)

GetByLoaderWithTtl can take a per key loader function (i.e. to propagate context)

func (*Cache) GetItems

func (cache *Cache) GetItems() map[string]interface{}

GetItems returns a copy of all items in the cache. Returns nil when the cache has been closed.

func (*Cache) GetKeys

func (cache *Cache) GetKeys() []string

GetKeys returns all keys of items in the cache. Returns nil when the cache has been closed.

func (*Cache) GetMetrics

func (cache *Cache) GetMetrics() Metrics

GetMetrics exposes the metrics of the cache. This is a snapshot copy of the metrics.

func (*Cache) GetWithTTL

func (cache *Cache) GetWithTTL(key KeyProvider) (interface{}, time.Duration, error)

GetWithTTL has exactly the same behaviour as Get but also returns the remaining TTL for a specific item at the moment its retrieved

func (*Cache) Purge

func (cache *Cache) Purge() error

Purge will remove all entries

func (*Cache) Remove

func (cache *Cache) Remove(key string) error

Remove removes an item from the cache if it exists, triggers expiration callback when set. Can return ErrNotFound if the entry was not present.

func (*Cache) Set

func (cache *Cache) Set(key string, data interface{}) error

Set is a thread-safe way to add new items to the map.

func (*Cache) SetCacheSizeLimit

func (cache *Cache) SetCacheSizeLimit(limit int)

SetCacheSizeLimit sets a limit to the amount of cached items. If a new item is getting cached, the closes item to being timed out will be replaced Set to 0 to turn off

func (*Cache) SetCheckExpirationCallback

func (cache *Cache) SetCheckExpirationCallback(callback CheckExpireCallback)

SetCheckExpirationCallback sets a callback that will be called when an item is about to expire in order to allow external code to decide whether the item expires or remains for another TTL cycle

func (*Cache) SetExpirationCallback

func (cache *Cache) SetExpirationCallback(callback ExpireCallback)

SetExpirationCallback sets a callback that will be called when an item expires

func (*Cache) SetExpirationReasonCallback

func (cache *Cache) SetExpirationReasonCallback(callback ExpireReasonCallback)

SetExpirationReasonCallback sets a callback that will be called when an item expires, includes reason of expiry

func (*Cache) SetLoaderFunction

func (cache *Cache) SetLoaderFunction(loader LoaderFunction)

SetLoaderFunction allows you to set a function to retrieve cache misses. The signature matches that of the Get function. Additional Get calls on the same key block while fetching is in progress (groupcache style).

func (*Cache) SetNewItemCallback

func (cache *Cache) SetNewItemCallback(callback ExpireCallback)

SetNewItemCallback sets a callback that will be called when a new item is added to the cache

func (*Cache) SetTTL

func (cache *Cache) SetTTL(ttl time.Duration) error

SetTTL sets the global TTL value for items in the cache, which can be overridden at the item level.

func (*Cache) SetWithTTL

func (cache *Cache) SetWithTTL(key string, data interface{}, ttl time.Duration) error

SetWithTTL is a thread-safe way to add new items to the map with individual ttl.

func (*Cache) SkipTTLExtensionOnHit

func (cache *Cache) SkipTTLExtensionOnHit(value bool)

SkipTTLExtensionOnHit allows the user to change the cache behaviour. When this flag is set to true it will no longer extend TTL of items when they are retrieved using Get, or when their expiration condition is evaluated using SetCheckExpirationCallback.

func (*Cache) Touch

func (cache *Cache) Touch(key string) error

Touch resets the TTL of the key when it exists, returns ErrNotFound if the key is not present.

type CheckExpireCallback

type CheckExpireCallback func(key string, value interface{}) bool

CheckExpireCallback is used as a callback for an external check on item expiration

type EvictionReason

type EvictionReason int

EvictionReason is an enum that explains why an item was evicted

const (
	// Removed : explicitly removed from cache via API call
	Removed EvictionReason = iota
	// EvictedSize : evicted due to exceeding the cache size
	EvictedSize
	// Expired : the time to live is zero and therefore the item is removed
	Expired
	// Closed : the cache was closed
	Closed
)

func EvictionReasonString

func EvictionReasonString(s string) (EvictionReason, error)

EvictionReasonString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func EvictionReasonValues

func EvictionReasonValues() []EvictionReason

EvictionReasonValues returns all values of the enum

func (EvictionReason) IsAEvictionReason

func (i EvictionReason) IsAEvictionReason() bool

IsAEvictionReason returns "true" if the value is listed in the enum definition. "false" otherwise

func (EvictionReason) String

func (i EvictionReason) String() string

type ExpireCallback

type ExpireCallback func(key string, value interface{})

ExpireCallback is used as a callback on item expiration or when notifying of an item new to the cache Note that ExpireReasonCallback will be the successor of this function in the next major release.

type ExpireReasonCallback

type ExpireReasonCallback func(key string, reason EvictionReason, value interface{})

ExpireReasonCallback is used as a callback on item expiration with extra information why the item expired.

type KeyProvider

type KeyProvider interface {
	GetKey() string
}

func NewSimpleKey

func NewSimpleKey(key string) KeyProvider

type LoaderFunction

type LoaderFunction func(keyProvider KeyProvider) (data interface{}, ttl time.Duration, err error)

LoaderFunction can be supplied to retrieve an item where a cache miss occurs. Supply an item specific ttl or Duration.Zero

type Metrics

type Metrics struct {
	// succesful inserts
	Inserted int64
	// retrieval attempts
	Retrievals int64
	// all get calls that were in the cache (excludes loader invocations)
	Hits int64
	// entries not in cache (includes loader invocations)
	Misses int64
	// items removed from the cache in any way
	Evicted int64
}

Metrics contains common cache metrics so you can calculate hit and miss rates

type SimpleCache

type SimpleCache interface {
	Get(key KeyProvider) (interface{}, error)
	GetWithTTL(key KeyProvider) (interface{}, time.Duration, error)
	Set(key string, data interface{}) error
	SetTTL(ttl time.Duration) error
	SetWithTTL(key string, data interface{}, ttl time.Duration) error
	Remove(key string) error
	Close() error
	Purge() error
}

SimpleCache interface enables a quick-start. Interface for basic usage.

Jump to

Keyboard shortcuts

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