cache

package module
v3.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2023 License: MIT Imports: 6 Imported by: 0

README

go-cache

Go Reference

sylr.dev/cache fork disclaimer

This module is a fork of github.com/patrickmn/go-cache/.

Synopsys

go-cache is an in-memory key:value store/cache similar to memcached that is suitable for applications running on a single machine.

This implementation uses go 1.18 type parameters (generics).

Its major advantage is that, being essentially a thread-safe map[string]interface{} with expiration times, it doesn't need to serialize or transmit its contents over the network.

Any object can be stored, for a given duration or forever, and the cache can be safely used by multiple goroutines.

Installation
gotip get sylr.dev/cache/v3
Reference

The API reference can be found at http://pkg.go.dev/sylr.dev/cache/v3.

Examples

See example_test.go for some usage examples.

Documentation

Index

Examples

Constants

View Source
const (
	// NoExpiration for use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	// DefaultExpiration for use with functions that take an expiration time. Equivalent to
	// passing in the same expiration duration as was given to New() or
	// NewFrom() when the cache was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)

Variables

View Source
var (
	ErrNotFound = errors.New("item not found")
)

Functions

This section is empty.

Types

type AnyCache

type AnyCache[T any] struct {
	// contains filtered or unexported fields
}

AnyCache implements AnyCacher

Example (Any)
// Create a generic cache with a default expiration time of 5 minutes
// All items are cached as interface{} so they need to be cast back to their
// original type when retrieved.
c := cache.NewAnyCacher[any](5*time.Minute, 10*time.Minute)

myStruct := &MyStruct{"MySuperStruct"}

c.Set("MySuperStruct", myStruct, 0)

myRawCachedStruct, found := c.Get("MySuperStruct")

if found {
	// Casting the retrieved object back to its original type
	myCachedStruct := myRawCachedStruct.(*MyStruct)
	fmt.Printf("%s", myCachedStruct.Name)
} else {
	fmt.Printf("Error: MySuperStruct not found in cache")
}
Output:

MySuperStruct

func New

func New[T any](defaultExpiration, cleanupInterval time.Duration) *AnyCache[T]

New[T](...) is an alias for NewAny[T](...).

func NewAny

func NewAny[T any](defaultExpiration, cleanupInterval time.Duration) *AnyCache[T]

NewAny[T any](...) returns a new AnyCache[T] with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

func NewAnyFrom

func NewAnyFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *AnyCache[T]

NewAnyFrom[T any]()... returns a new *AnyCache[T] with a given default expiration duration and cleanup interval. If the expiration duration is less than one (or NoExpiration), the items in the cache never expire (by default), and must be deleted manually. If the cleanup interval is less than one, expired items are not deleted from the cache before calling c.DeleteExpired().

NewFrom() also accepts an items map which will serve as the underlying map for the cache. This is useful for starting from a deserialized cache (serialized using e.g. gob.Encode() on c.Items()), or passing in e.g. make(map[string]Item, 500) to improve startup performance when the cache is expected to reach a certain minimum size.

Only the cache's methods synchronize access to this map, so it is not recommended to keep any references to the map around after creating a cache. If need be, the map can be accessed at a later point using c.Items() (subject to the same caveat.)

Note regarding serialization: When using e.g. gob, make sure to gob.Register() the individual types stored in the cache before encoding a map retrieved with c.Items(), and to register those same types before decoding a blob containing an items map.

func NewFrom

func NewFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *AnyCache[T]

NewFrom[T any](...) is an alias for NewAnyFrom[T](...).

func (AnyCache) Add

func (c AnyCache) Add(k string, x T, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

func (AnyCache) Delete

func (c AnyCache) Delete(k string)

Delete deletes an item from the cache. Does nothing if the key is not in the cache.

func (AnyCache) DeleteExpired

func (c AnyCache) DeleteExpired()

DeleteExpired deletes all expired items from the cache.

func (AnyCache) Flush

func (c AnyCache) Flush()

Flush Delete all items from the cache.

func (AnyCache) Get

func (c AnyCache) Get(k string) (T, bool)

Get gets an item from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (AnyCache) GetWithExpiration

func (c AnyCache) GetWithExpiration(k string) (T, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (AnyCache) ItemCount

func (c AnyCache) ItemCount() int

ItemCount returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up.

func (AnyCache) Items

func (c AnyCache) Items() map[string]Item[T]

Items copies all unexpired items in the cache into a new map and returns it.

func (AnyCache) OnEvicted

func (c AnyCache) OnEvicted(f func(string, T))

OnEvicted sets an (optional) function that is called with the key and value when an item is evicted from the cache. (Including when it is deleted manually, but not when it is overwritten.) Set to nil to disable.

func (AnyCache) Replace

func (c AnyCache) Replace(k string, x T, d time.Duration) error

Replace replaces a new value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise.

func (AnyCache) Set

func (c AnyCache) Set(k string, x T, d time.Duration)

Set adds an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires.

func (AnyCache) SetDefault

func (c AnyCache) SetDefault(k string, x T)

SetDefault adds an item to the cache, replacing any existing item, using the default expiration.

type AnyCacher

type AnyCacher[T any] interface {
	// Delete all expired items from the cache.
	DeleteExpired()
	// Add an item to the cache only if an item doesn't already exist for the given
	// key, or if the existing item has expired. Returns an error otherwise.
	Add(k string, x T, d time.Duration) error
	// Delete an item from the cache. Does nothing if the key is not in the cache.
	Delete(k string)
	// Delete all items from the cache.
	Flush()
	// Get an item from the cache. Returns the item or nil, and a bool indicating
	// whether the key was found.
	Get(k string) (T, bool)
	// GetWithExpiration returns an item and its expiration time from the cache.
	// It returns the item or nil, the expiration time if one is set (if the item
	// never expires a zero value for time.Time is returned), and a bool indicating
	// whether the key was found.
	GetWithExpiration(k string) (T, time.Time, bool)
	// ItemCount returns the number of items in the cache.
	ItemCount() int
	// Copies all unexpired items in the cache into a new map and returns it.
	Items() map[string]Item[T]
	// Set a new value for the cache key only if it already exists, and the existing
	// item hasn't expired. Returns an error otherwise.
	Replace(k string, x T, d time.Duration) error
	// Add an item to the cache, replacing any existing item, using the default
	// expiration.
	SetDefault(k string, x T)
	// Add an item to the cache, replacing any existing item. If the duration is 0
	// (DefaultExpiration), the cache's default expiration time is used. If it is -1
	// (NoExpiration), the item never expires.
	Set(k string, x T, d time.Duration)
	// Sets an (optional) function that is called with the key and value when an
	// item is evicted from the cache. (Including when it is deleted manually, but
	// not when it is overwritten.) Set to nil to disable.
	OnEvicted(f func(string, T))
}
Example (CustomStruct)
// Create a cache with a default expiration time of 5 minutes, and which
c := cache.NewAnyCacher[*MyStruct](5*time.Minute, 10*time.Minute)

myStruct := &MyStruct{"MySuperStruct"}

c.Set("MySuperStruct", myStruct, 0)

myCachedStruct, found := c.Get("MySuperStruct")

if found {
	fmt.Printf("%s", myCachedStruct.Name)
} else {
	fmt.Printf("Error: MySuperStruct not found in cache")
}
Output:

MySuperStruct
Example (String)
// Create a string cache with a default expiration time of 5 minutes.
c := cache.NewAnyCacher[string](5*time.Minute, 10*time.Minute)

c.Set("string", "MySuperString", 0)

mySuperString, found := c.Get("string")

if found {
	fmt.Printf("%s", mySuperString)
} else {
	fmt.Printf("Error: MySuperStruct not found in cache")
}
Output:

MySuperString

func NewAnyCacher

func NewAnyCacher[T any](defaultExpiration, cleanupInterval time.Duration) AnyCacher[T]

NewAnyCacher[T any](...) returns an AnyCacher[T] interface.

func NewAnyCacherFrom

func NewAnyCacherFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) AnyCacher[T]

NewAnyCacherFrom[T any](...) returns a AnyCacher[T] interface.

func NewNoopAnyCacher

func NewNoopAnyCacher[T any](defaultExpiration, cleanupInterval time.Duration) AnyCacher[T]

NewAnyCacher returns an AnyCacher[T] interface

func NewNoopAnyCacherFrom

func NewNoopAnyCacherFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) AnyCacher[T]

NewAnyCacherFrom returns a AnyCacher[T] interface.

type Item

type Item[T any] struct {
	Object     T
	Expiration int64
}

Item ...

func (*Item[T]) Expired

func (item *Item[T]) Expired() bool

Expired returns true if the item has expired.

type NoopCache

type NoopCache[T any] struct{}

Cache implements Cacher.

func NewNoop

func NewNoop[T any](defaultExpiration, cleanupInterval time.Duration) *NoopCache[T]

New returns a new NoopCache[T]

func NewNoopFrom

func NewNoopFrom[T any](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *NoopCache[T]

NewNoopFrom returns a new *NoopCache[T] with a given default expiration duration and cleanup interval.

func (*NoopCache[T]) Add

func (c *NoopCache[T]) Add(k string, x T, d time.Duration) error

Add an item to the cache only if an item doesn't already exist for the given key, or if the existing item has expired. Returns an error otherwise.

func (*NoopCache[T]) Delete

func (c *NoopCache[T]) Delete(k string)

Delete deletes an item from the cache. Does nothing if the key is not in the cache.

func (*NoopCache[T]) DeleteExpired

func (c *NoopCache[T]) DeleteExpired()

DeleteExpired deletes all expired items from the cache.

func (*NoopCache[T]) Flush

func (c *NoopCache[T]) Flush()

Flush Delete all items from the cache.

func (*NoopCache[T]) Get

func (c *NoopCache[T]) Get(k string) (T, bool)

Get gets an item from the cache. Returns the item or nil, and a bool indicating whether the key was found.

func (*NoopCache[T]) GetWithExpiration

func (c *NoopCache[T]) GetWithExpiration(k string) (T, time.Time, bool)

GetWithExpiration returns an item and its expiration time from the cache. It returns the item or nil, the expiration time if one is set (if the item never expires a zero value for time.Time is returned), and a bool indicating whether the key was found.

func (*NoopCache[T]) ItemCount

func (c *NoopCache[T]) ItemCount() int

ItemCount returns the number of items in the cache. This may include items that have expired, but have not yet been cleaned up.

func (*NoopCache[T]) Items

func (c *NoopCache[T]) Items() map[string]Item[T]

Items copies all unexpired items in the cache into a new map and returns it.

func (*NoopCache[T]) OnEvicted

func (c *NoopCache[T]) OnEvicted(f func(string, T))

OnEvicted sets an (optional) function that is called with the key and value when an item is evicted from the cache. (Including when it is deleted manually, but not when it is overwritten.) Set to nil to disable.

func (*NoopCache[T]) Replace

func (c *NoopCache[T]) Replace(k string, x T, d time.Duration) error

Replace replaces a new value for the cache key only if it already exists, and the existing item hasn't expired. Returns an error otherwise.

func (*NoopCache[T]) Set

func (c *NoopCache[T]) Set(k string, x T, d time.Duration)

Set adds an item to the cache, replacing any existing item. If the duration is 0 (DefaultExpiration), the cache's default expiration time is used. If it is -1 (NoExpiration), the item never expires.

func (*NoopCache[T]) SetDefault

func (c *NoopCache[T]) SetDefault(k string, x T)

SetDefault adds an item to the cache, replacing any existing item, using the default expiration.

type NoopNumericCache

type NoopNumericCache[T Numeric] struct {
	NoopCache[T]
}

Cache implements Cacher

func NewNoopNumeric

func NewNoopNumeric[T Numeric](defaultExpiration, cleanupInterval time.Duration) *NoopNumericCache[T]

NewAnyCacher returns a *NoopNumericCache[T]

func NewNoopNumericFrom

func NewNoopNumericFrom[T Numeric](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *NoopNumericCache[T]

NewAnyCacherFrom returns a *NumericCache[T].

func (*NoopNumericCache[T]) Decrement

func (c *NoopNumericCache[T]) Decrement(k string, n T) (T, error)

Decrement decrements an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (*NoopNumericCache[T]) Increment

func (c *NoopNumericCache[T]) Increment(k string, n T) (T, error)

Increment increments an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

type Numeric

type Numeric interface {
	constraints.Integer | constraints.Float
}

type NumericCache

type NumericCache[T Numeric] struct {
	// contains filtered or unexported fields
}

AnyCache implements AnyCacher

Example (Float64)
// Create a float64 cache with a default expiration time of 5 minutes.
c := cache.NewNumericCacher[float64](5*time.Minute, 10*time.Minute)
key := "universeAnswer"

c.Set(key, 42.0, 0)
c.Increment(key, 1.0)
c.Decrement(key, 1.0)

universeAnswer, found := c.Get(key)

if found {
	fmt.Printf("%.1f", universeAnswer)
} else {
	fmt.Printf("Error: %s not found in cache", key)
}
Output:

42.0

func NewNumeric

func NewNumeric[T Numeric](defaultExpiration, cleanupInterval time.Duration) *NumericCache[T]

NewNumeric[T Numeric](...) returns a *NumericCache[T].

func NewNumericFrom

func NewNumericFrom[T Numeric](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) *NumericCache[T]

NewNumericFrom[T Numeric](...) returns a *NumericCache[T].

func (NumericCache) Decrement

func (c NumericCache) Decrement(k string, n T) (T, error)

Decrement decrements an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to decrement it by n. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementInt64.

func (NumericCache) Increment

func (c NumericCache) Increment(k string, n T) (T, error)

Increment increments an item of type int, int8, int16, int32, int64, uintptr, uint, uint8, uint32, or uint64, float32 or float64 by n. Returns an error if the item's value is not an integer, if it was not found, or if it is not possible to increment it by n. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementInt64.

type NumericCacher

type NumericCacher[T Numeric] interface {
	AnyCacher[T]
	// Decrement an item of type int8 by n. Returns an error if the item's value is
	// not an int8, or if it was not found. If there is no error, the decremented
	// value is returned.
	Decrement(k string, n T) (T, error)
	// Increment an item of type int32 by n. Returns an error if the item's value is
	// not an int32, or if it was not found. If there is no error, the incremented
	// value is returned.
	Increment(k string, n T) (T, error)
}
Example (Int8)
// Create a float64 cache with a default expiration time of 5 minutes.
c := cache.NewNumericCacher[int8](5*time.Minute, 10*time.Minute)
key := "universeAnswer"

c.Set(key, 42, 0)
c.Increment(key, 1)
c.Decrement(key, 1)

universeAnswer, found := c.Get("universeAnswer")

if found {
	fmt.Printf("%d", universeAnswer)
} else {
	fmt.Printf("Error: universeAnswer not found in cache")
}
Output:

42

func NewNoopNumericCacher

func NewNoopNumericCacher[T Numeric](defaultExpiration, cleanupInterval time.Duration) NumericCacher[T]

NewCacher returns a NumericCacher[T] interface

func NewNoopNumericCacherFrom

func NewNoopNumericCacherFrom[T Numeric](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) NumericCacher[T]

NewAnyCacherFrom returns a NumericCacher[T] interface.

func NewNumericCacher

func NewNumericCacher[T Numeric](defaultExpiration, cleanupInterval time.Duration) NumericCacher[T]

NewNumericCacher[T Numeric](...) returns a NumericCacher[T] interface.

func NewNumericCacherFrom

func NewNumericCacherFrom[T Numeric](defaultExpiration, cleanupInterval time.Duration, items map[string]Item[T]) NumericCacher[T]

NewNumericCacherFrom[T Numeric](...) returns a NumericCacher[T] interface.

Jump to

Keyboard shortcuts

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