Documentation ¶
Overview ¶
Package cache is a simple implementation of in-memory key-value storage based on golang map type. This package allows to setup various options, such as values expiration time (default, individual), max number of entries in cache, max byte size of data which can be stored in cache. Data can be dumped into json file and restored from it with all saved metadata. Cache usage is thread safe and it can be accessed from multiple goroutines.
Index ¶
- Variables
- func Decrement[T Integer](c *Cache, k string, n T) (T, error)
- func Increment[T Integer](c *Cache, k string, n T) (T, error)
- func WithCleanupInteval(d time.Duration) cacheOptFn
- func WithDataSize(fn func(string, any) (uint64, error)) cacheOptFndeprecated
- func WithDataSizeFn(fn func(string, any) (uint64, error)) cacheOptFn
- func WithDefaultLifetime(lt uint64) cacheOptFn
- func WithLifetime(lt uint64) unitOptFn
- func WithMaxSize(ms uint64) cacheOptFn
- func WithMaxUnits(mu uint64) cacheOptFn
- func WithOnEviction(fn func(string, any)) cacheOptFndeprecated
- func WithOnEvictionFn(fn func(string, any)) cacheOptFn
- func WithSize(s uint64) unitOptFn
- func WithoutJanitorEviction(co *cacheOpts)
- type Cache
- func (c *Cache) Add(k string, a any, opts ...unitOptFn) error
- func (c *Cache) Alive() map[string]any
- func (c *Cache) ChangeDefaultLifeTime(lt uint64)
- func (c *Cache) ChangeJanitorOnEviction(b bool)
- func (c *Cache) ChangeMaxLength(ml uint64) error
- func (c *Cache) ChangeMaxSize(i uint64) error
- func (c *Cache) ChangeOnEviction(fn func(string, any))
- func (c *Cache) ChangeOnEvictionFn(fn func(string, any))
- func (c *Cache) ChangeSizeFn(fn func(string, any) (uint64, error))
- func (c *Cache) Delete(k string)
- func (c *Cache) DeleteAll()
- func (c *Cache) DeleteExpired()
- func (c *Cache) Get(k string) (any, error)
- func (c *Cache) Length() int
- func (c *Cache) Load(r io.Reader) error
- func (c *Cache) OrderCleaning()
- func (c *Cache) Remove(k string)
- func (c *Cache) RemoveAll()
- func (c *Cache) RemoveExpired()
- func (c *Cache) Rename(oldKey, newKey string) error
- func (c *Cache) Replace(k string, a any) error
- func (c *Cache) RescheduleCleaning(d time.Duration) error
- func (c *Cache) Revive(k string) error
- func (c *Cache) ReviveUntil(k string, lt uint64) error
- func (c *Cache) Save(w io.Writer) error
- func (c *Cache) Scan(sub string) map[string]any
- func (c *Cache) ScanFunc(fn func(string) bool) map[string]any
- func (c *Cache) Set(k string, a any, opts ...unitOptFn) error
- func (c *Cache) Size() uint64
- func (c *Cache) Snapshot() map[string]any
- func (c *Cache) Stats() *Stats
- func (c *Cache) StopCleaning()
- type Integer
- type Stats
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( ErrDuration = errors.New("non-positive duration") ErrExists = errors.New("already exists") ErrExpired = errors.New("is expired") ErrNotExists = errors.New("does not exist") ErrMaxSize = errors.New("max size limit") ErrMaxLength = errors.New("max data limit") ErrNotInt = errors.New("data type is not integer") )
Functions ¶
func Decrement ¶
Decrement decrements data of the given key with n. Returns error if key does not exist, was expired or if type assertion to Integer has failed.
func Increment ¶
Increment increments data of the given key with n. Returns error if key does not exist, was expired or if type assertion to Integer has failed.
func WithCleanupInteval ¶
WithCleanupInteval sets interval for janitor to clean expired keys.
func WithDataSize
deprecated
WithDataSize sets function which defines data size.
Deprecated: use WithDataSizeFn instead.
func WithDataSizeFn ¶ added in v1.0.1
WithDataSizeFn sets function which defines data size.
func WithDefaultLifetime ¶
func WithDefaultLifetime(lt uint64) cacheOptFn
WithDefaultLifetime sets default lifetime for key in cache.
func WithLifetime ¶
func WithLifetime(lt uint64) unitOptFn
WithLifetime sets custom lifetime for cache key.
func WithMaxSize ¶
func WithMaxSize(ms uint64) cacheOptFn
WithMaxSize sets maximum cache data size in bytes.
func WithMaxUnits ¶
func WithMaxUnits(mu uint64) cacheOptFn
WithMaxUnits sets maxixum number of keys, which can be stored in cache.
func WithOnEviction
deprecated
WithOnEviction sets custom function which is applied when key is being deleted from cache.
Deprecated: use WithOnEvictionFn instead.
func WithOnEvictionFn ¶ added in v1.0.1
WithOnEvictionFn sets custom function which is applied when key is being deleted from cache.
func WithSize ¶
func WithSize(s uint64) unitOptFn
WithSize sets custom size for key data. If set, cache will ignore size calculation and use passed value. Adds default metadata size.
func WithoutJanitorEviction ¶
func WithoutJanitorEviction(co *cacheOpts)
WithoutJanitorEviction sets janitor to clean expired keys without applying on eviction function even if it was set.
Types ¶
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Example ¶
c := New() if err := c.Set("foo", "bar"); err != nil { // Process error... } data, err := c.Get("foo") if err != nil { // Process error... } fmt.Println(data) // Prints: "bar".
Output:
Example (SaveLoad) ¶
c := New( WithDefaultLifetime(uint64(time.Hour)), WithMaxSize(1028), ) if err := c.Set("foo", "simple string"); err != nil { // Process error... } type test struct { Str string `json:"str"` } testStruct := &test{"string in struct"} if err := c.Set("foo2", testStruct); err != nil { // Process error... } if err := c.Set("foo3", []string{"string in slice"}); err != nil { // Process error... } if err := c.Set("foo4", map[string]string{"bar": "string in map"}); err != nil { // Process error... } dumpFile := "dump.json" f, err := os.Create(dumpFile) if err != nil { // Process error... } if err := c.Save(f); err != nil { f.Close() // Process error... } f.Close() c.RemoveAll() f, err = os.Open(dumpFile) if err != nil { // Process error... } defer f.Close() if err := c.Load(f); err != nil { // Process error... } str, err := c.Get("foo") if err != nil { // Process error... } fmt.Println(str) // Prints: "simple string". if str, err := c.Get("foo2"); err != nil { // Process error... } else { jsonData, err := json.Marshal(str) if err != nil { // Process error... } var structData test if err := json.Unmarshal(jsonData, &structData); err != nil { // Process error... } // structData.Str == "string in struct". } if str, err := c.Get("foo3"); err != nil { // Process error... } else { sl := make([]string, len(str.([]any))) for i, el := range str.([]any) { sl[i] = el.(string) } // sl[0] == "string in slice". } if str, err := c.Get("foo4"); err != nil { // Process error... } else { m := make(map[string]string, len(str.(map[string]any))) for k, v := range str.(map[string]any) { m[k] = v.(string) } // m["bar"] == "string in map". }
Output:
Example (WithOptions) ¶
c := New( WithCleanupInteval(time.Minute), WithDefaultLifetime(uint64(500*time.Millisecond)), ) if err := c.Set("foo", "bar"); err != nil { // Process error... } time.Sleep(1 * time.Second) data, err := c.Get("foo") fmt.Println(data) // Prints: "bar". fmt.Println(err) // Prints: key "foo": is expired. c.RemoveExpired() _, err = c.Get("foo") fmt.Println(err) // Prints: key "foo": does not exist. if err := c.Set("foo", "bar", WithLifetime(uint64(1*time.Second))); err != nil { // Process error... } time.Sleep(500 * time.Millisecond) m := c.Alive() if v, ok := m["foo"]; ok { fmt.Println(v) // Prints: "bar". }
Output:
func (*Cache) ChangeDefaultLifeTime ¶
ChangeDefaultLifeTime updates cache default options with new default lifetime for key. Does not affect keys already in cache.
func (*Cache) ChangeJanitorOnEviction ¶
ChangeJanitorOnEviction updates cache default options with new janitor expiried keys removal behavior. Allows to control if janitor should apply on eviction function even if it was set. Restart janitor if it's currently running.
func (*Cache) ChangeMaxLength ¶
ChangeMaxLength updates cache default options with new max number of keys. Returns ErrMaxLength if new value is lower than number of keys already in cache.
func (*Cache) ChangeMaxSize ¶
ChangeMaxSize updates cache default options with new cache max size in bytes.
func (*Cache) ChangeOnEviction ¶
ChangeOnEviction updates cache default options with new function which runs when key is being cleaned after expiration. If janitor is cleaning cache, this function will wait until it finishes, before changing on eviction function. Deprecated: use [ChangeOnEvictionFn] instead.
func (*Cache) ChangeOnEvictionFn ¶ added in v1.0.1
ChangeOnEvictionFn updates cache default options with new function which runs when key is being cleaned after expiration. If janitor is cleaning cache, this function will wait until it finishes, before changing on eviction function.
func (*Cache) ChangeSizeFn ¶
ChangeSizeFn updates cache default options with new function to define data size. Does not affect keys already in cache.
func (*Cache) Delete ¶
Delete removes key with given name from cache. Do nothing if key does not exist. Applies on eviction function if it was set.
func (*Cache) DeleteAll ¶
func (c *Cache) DeleteAll()
DeleteAll removes all keys from cache applying on eviction function if it was set.
func (*Cache) DeleteExpired ¶
func (c *Cache) DeleteExpired()
DeleteExpired removes only expired keys applying on eviction function if it was set.
func (*Cache) Get ¶
Get returns data of the given key. If key does not exist then ErrNotExists will be returned. If key is already expired, but was not yet cleaned, returns data and ErrExpired as error.
func (*Cache) OrderCleaning ¶
func (c *Cache) OrderCleaning()
OrderCleaning stops current janitor if it was set and starts a new one with cache default cleanup interval.
func (*Cache) Remove ¶
Remove removes key with given name from cache. Do nothing if key does not exist. Does not apply on eviction function even if it was set.
func (*Cache) RemoveAll ¶
func (c *Cache) RemoveAll()
RemoveAll removes all keys from cache. Does not apply on eviction function even if it was set. Runs GC to collect released memory.
func (*Cache) RemoveExpired ¶
func (c *Cache) RemoveExpired()
RemoveExpired removes only expired keys. Does not apply on eviction function even if it was set.
func (*Cache) Rename ¶
Rename renames old key with a new name only if given key exists in cache and is not expired.
func (*Cache) Replace ¶
Replace replaces data of the given key only if this key exists in cache and is not expired.
func (*Cache) RescheduleCleaning ¶
RescheduleCleaning stops current janitor if it was set, updates cache default cleanup interval with given duration and starts a new janitor.
func (*Cache) ReviveUntil ¶
ReviveUntil prolongs lifetime of the key with specified value.
func (*Cache) Scan ¶
Scan scans current [Snapshot] of the cache data and returns key-value map if key contains given sub-string.
func (*Cache) ScanFunc ¶
ScanFunc scans current [Snapshot] of the cache and returns key-value map if given func returns true for a key.
func (*Cache) Set ¶
Set saves data in cache with given key and options. If key already exists it will be replaced without warnings.
func (*Cache) StopCleaning ¶
func (c *Cache) StopCleaning()
StopCleaning stops current janitor if it was set. This function waits until janitor is unlocked if it is in cleaning progress.