cache

package
v1.7.6 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2025 License: MIT, Apache-2.0, MIT Imports: 10 Imported by: 0

README

freecache 号称0gc gcache 用的人少 go-cache 实现简单,最快的

ristretto 宣称性能比freecache好,为啥确定存在的值还有命中失败的时候

BenchmarkFree BenchmarkFree-4 4511440 259.5 ns/op BenchmarkGCache BenchmarkGCache-4 8045618 152.3 ns/op BenchmarkGoCache BenchmarkGoCache-4 12903280 95.33 ns/op BenchmarkRistretto BenchmarkRistretto-4 2098572 476.9 ns/op

GCache

wercker statusGoDoc

Cache library for golang. It supports expirable Cache, LFU, LRU and ARC.

Features

  • Supports expirable Cache, LFU, LRU and ARC.

  • Goroutine safe.

  • Supports event handlers which evict, purge, and add entry. (Optional)

  • Automatically load cache if it doesn't exists. (Optional)

Install

$ go get github.com/bluele/gcache

Example

Manually set a key-value pair.
package main

import (
  "github.com/bluele/gcache"
  "fmt"
)

func main() {
  gc := gcache.New(20).
    LRU().
    Build()
  gc.Set("key", "ok")
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok
Manually set a key-value pair, with an expiration time.
package main

import (
  "github.com/bluele/gcache"
  "fmt"
  "time"
)

func main() {
  gc := gcache.New(20).
    LRU().
    Build()
  gc.SetWithExpire("key", "ok", time.Second*10)
  value, _ := gc.Get("key")
  fmt.Println("Get:", value)

  // Wait for value to expire
  time.Sleep(time.Second*10)

  value, err = gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok
// 10 seconds later, new attempt:
panic: ErrKeyNotFound
Automatically load value
package main

import (
  "github.com/bluele/gcache"
  "fmt"
)

func main() {
  gc := gcache.New(20).
    LRU().
    LoaderFunc(func(key interface{}) (interface{}, error) {
      return "ok", nil
    }).
    Build()
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
}
Get: ok
Automatically load value with expiration
package main

import (
  "fmt"
  "time"

  "github.com/bluele/gcache"
)

func main() {
  var evictCounter, loaderCounter, purgeCounter int
  gc := gcache.New(20).
    LRU().
    LoaderExpireFunc(func(key interface{}) (interface{}, *time.Duration, error) {
      loaderCounter++
      expire := 1 * time.Second
      return "ok", &expire, nil
    }).
    EvictedFunc(func(key, value interface{}) {
      evictCounter++
      fmt.Println("evicted key:", key)
    }).
    PurgeVisitorFunc(func(key, value interface{}) {
      purgeCounter++
      fmt.Println("purged key:", key)
    }).
    Build()
  value, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
  time.Sleep(1 * time.Second)
  value, err = gc.Get("key")
  if err != nil {
    panic(err)
  }
  fmt.Println("Get:", value)
  gc.Purge()
  if loaderCounter != evictCounter+purgeCounter {
    panic("bad")
  }
}
Get: ok
evicted key: key
Get: ok
purged key: key

Cache Algorithm

  • Least-Frequently Used (LFU)

Discards the least frequently used items first.

func main() {
  // size: 10
  gc := gcache.New(10).
    LFU().
    Build()
  gc.Set("key", "value")
}
  • Least Recently Used (LRU)

Discards the least recently used items first.

func main() {
  // size: 10
  gc := gcache.New(10).
    LRU().
    Build()
  gc.Set("key", "value")
}
  • Adaptive Replacement Cache (ARC)

Constantly balances between LRU and LFU, to improve the combined result.

detail: http://en.wikipedia.org/wiki/Adaptive_replacement_cache

func main() {
  // size: 10
  gc := gcache.New(10).
    ARC().
    Build()
  gc.Set("key", "value")
}
  • SimpleCache (Default)

SimpleCache has no clear priority for evict cache. It depends on key-value map order.

func main() {
  // size: 10
  gc := gcache.New(10).Build()
  gc.Set("key", "value")
  v, err := gc.Get("key")
  if err != nil {
    panic(err)
  }
}

Loading Cache

If specified LoaderFunc, values are automatically loaded by the cache, and are stored in the cache until either evicted or manually invalidated.

func main() {
  gc := gcache.New(10).
    LRU().
    LoaderFunc(func(key interface{}) (interface{}, error) {
      return "value", nil
    }).
    Build()
  v, _ := gc.Get("key")
  // output: "value"
  fmt.Println(v)
}

GCache coordinates cache fills such that only one load in one process of an entire replicated set of processes populates the cache, then multiplexes the loaded value to all callers.

Expirable cache

func main() {
  // LRU cache, size: 10, expiration: after a hour
  gc := gcache.New(10).
    LRU().
    Expiration(time.Hour).
    Build()
}

Event handlers

Evicted handler

Event handler for evict the entry.

func main() {
  gc := gcache.New(2).
    EvictedFunc(func(key, value interface{}) {
      fmt.Println("evicted key:", key)
    }).
    Build()
  for i := 0; i < 3; i++ {
    gc.Set(i, i*i)
  }
}
evicted key: 0
Added handler

Event handler for add the entry.

func main() {
  gc := gcache.New(2).
    AddedFunc(func(key, value interface{}) {
      fmt.Println("added key:", key)
    }).
    Build()
  for i := 0; i < 3; i++ {
    gc.Set(i, i*i)
  }
}
added key: 0
added key: 1
added key: 2

Author

Jun Kimura

Documentation

Index

Constants

View Source
const (
	TYPE_LRU    = "lru"
	TYPE_LFU    = "lfu"
	TYPE_ARC    = "arc"
	TYPE_Simple = "simple"
)
View Source
const (
	// For use with functions that take an expiration time.
	NoExpiration time.Duration = -1
	// 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 Simple was created (e.g. 5 minutes.)
	DefaultExpiration time.Duration = 0
)

Variables

View Source
var (
	KeyNotFoundError     = errors.New("key not found")
	KeyAlreadyExistError = errors.New("key already exist")
)

Functions

This section is empty.

Types

type ARC

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

Constantly balances between LRU and LFU, to improve the combined result.

func (*ARC) Flush

func (c *ARC) Flush()

Flush is used to completely clear the cache

func (*ARC) Get

func (c *ARC) Get(key any) (any, error)

Get a value from cache pool using key if it exists. If not exists and it has LoaderFunc, it will generate the value using you have specified LoaderFunc method returns value.

func (*ARC) GetALL

func (c *ARC) GetALL(checkExpired bool) map[any]any

GetALL returns all key-value pairs in the cache.

func (*ARC) GetIFPresent

func (c *ARC) GetIFPresent(key any) (any, error)

GetIFPresent gets a value from cache pool using key if it exists. If it dose not exists key, returns KeyNotFoundError. And send a request which refresh value for specified key if cache object has LoaderFunc.

func (*ARC) Has

func (c *ARC) Has(key any) bool

Has checks if key exists in cache

func (*ARC) Keys

func (c *ARC) Keys(checkExpired bool) []any

Keys returns a slice of the keys in the cache.

func (*ARC) Len

func (c *ARC) Len(checkExpired bool) int

Len returns the number of items in the cache.

func (*ARC) Purge

func (c *ARC) Purge()

Purge is used to completely clear the cache

func (*ARC) Remove

func (c *ARC) Remove(key any) bool

Remove removes the provided key from the cache.

func (*ARC) Set

func (c *ARC) Set(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

func (*ARC) SetNX

func (c *ARC) SetNX(k any, x any, d time.Duration) error

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

type AddedFunc

type AddedFunc func(any, any)

type Cache

type Cache interface {
	Set(key, value any, expiration time.Duration) error
	SetNX(key, value any, expiration time.Duration) error
	Get(key any) (any, error)
	GetALL(checkExpired bool) map[any]any

	Remove(key any) bool

	Keys(checkExpired bool) []any
	Len(checkExpired bool) int
	Has(key any) bool

	Purge()
	Flush()
	// contains filtered or unexported methods
}

type CacheBuilder

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

func New

func New(size int) *CacheBuilder

func (*CacheBuilder) ARC

func (cb *CacheBuilder) ARC() *CacheBuilder

func (*CacheBuilder) AddedFunc

func (cb *CacheBuilder) AddedFunc(addedFunc AddedFunc) *CacheBuilder

func (*CacheBuilder) Build

func (cb *CacheBuilder) Build() Cache

func (*CacheBuilder) EvictType

func (cb *CacheBuilder) EvictType(tp string) *CacheBuilder

func (*CacheBuilder) EvictedFunc

func (cb *CacheBuilder) EvictedFunc(evictedFunc EvictedFunc) *CacheBuilder

func (*CacheBuilder) Expiration

func (cb *CacheBuilder) Expiration(expiration time.Duration) *CacheBuilder

func (*CacheBuilder) Janitor

func (cb *CacheBuilder) Janitor(interval time.Duration) *CacheBuilder

func (*CacheBuilder) LFU

func (cb *CacheBuilder) LFU() *CacheBuilder

func (*CacheBuilder) LRU

func (cb *CacheBuilder) LRU() *CacheBuilder

func (*CacheBuilder) LoaderFunc

func (cb *CacheBuilder) LoaderFunc(loaderFunc LoaderFunc) *CacheBuilder

Set a loader function with expiration. loaderFunc: create a new value with this function if cached value is expired. If nil returned instead of time.Duration from loaderFunc than value will never expire.

func (*CacheBuilder) PurgeVisitorFunc

func (cb *CacheBuilder) PurgeVisitorFunc(purgeVisitorFunc PurgeVisitorFunc) *CacheBuilder

func (*CacheBuilder) Simple

func (cb *CacheBuilder) Simple() *CacheBuilder

type DeserializeFunc

type DeserializeFunc func(any, any) (any, error)

type EvictedFunc

type EvictedFunc func(any, any)

type Group

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

Group represents a class of work and forms a namespace in which units of work can be executed with duplicate suppression.

func (*Group) Do

func (g *Group) Do(key any, fn func() (any, error), isWait bool) (any, bool, error)

Do executes and returns the results of the given function, making sure that only one execution is in-flight for a given key at a time. If a duplicate comes in, the duplicate caller waits for the original to complete and receives the same results.

type LFU

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

Discards the least frequently used items first.

func (*LFU) Flush

func (c *LFU) Flush()

Flush is used to completely clear the cache

func (*LFU) Get

func (c *LFU) Get(key any) (any, error)

Get a value from cache pool using key if it exists. If it dose not exists key and has LoaderFunc, generate a value using `LoaderFunc` method returns value.

func (*LFU) GetALL

func (c *LFU) GetALL(checkExpired bool) map[any]any

GetALL returns all key-value pairs in the cache.

func (*LFU) GetIFPresent

func (c *LFU) GetIFPresent(key any) (any, error)

GetIFPresent gets a value from cache pool using key if it exists. If it dose not exists key, returns KeyNotFoundError. And send a request which refresh value for specified key if cache object has LoaderFunc.

func (*LFU) Has

func (c *LFU) Has(key any) bool

Has checks if key exists in cache

func (*LFU) Keys

func (c *LFU) Keys(checkExpired bool) []any

Keys returns a slice of the keys in the cache.

func (*LFU) Len

func (c *LFU) Len(checkExpired bool) int

Len returns the number of items in the cache.

func (*LFU) Purge

func (c *LFU) Purge()

Completely clear the cache

func (*LFU) Remove

func (c *LFU) Remove(key any) bool

Remove removes the provided key from the cache.

func (*LFU) Set

func (c *LFU) Set(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

func (*LFU) SetNX

func (c *LFU) SetNX(k any, x any, d time.Duration) error

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

type LRU

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

Discards the least recently used items first.

func (*LRU) Flush

func (c *LRU) Flush()

Flush is used to completely clear the cache

func (*LRU) Get

func (c *LRU) Get(key any) (any, error)

Get a value from cache pool using key if it exists. If it dose not exists key and has LoaderFunc, generate a value using `LoaderFunc` method returns value.

func (*LRU) GetALL

func (c *LRU) GetALL(checkExpired bool) map[any]any

GetALL returns all key-value pairs in the cache.

func (*LRU) GetIFPresent

func (c *LRU) GetIFPresent(key any) (any, error)

GetIFPresent gets a value from cache pool using key if it exists. If it dose not exists key, returns KeyNotFoundError. And send a request which refresh value for specified key if cache object has LoaderFunc.

func (*LRU) Has

func (c *LRU) Has(key any) bool

Has checks if key exists in cache

func (*LRU) Keys

func (c *LRU) Keys(checkExpired bool) []any

Keys returns a slice of the keys in the cache.

func (*LRU) Len

func (c *LRU) Len(checkExpired bool) int

Len returns the number of items in the cache.

func (*LRU) Purge

func (c *LRU) Purge()

Purge all expired items from the Simple.

func (*LRU) Remove

func (c *LRU) Remove(key any) bool

Remove removes the provided key from the cache.

func (*LRU) Set

func (c *LRU) Set(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

func (*LRU) SetNX

func (c *LRU) SetNX(k any, x any, d time.Duration) error

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

type LoaderFunc

type LoaderFunc func(any) (any, time.Duration, error)

type PurgeVisitorFunc

type PurgeVisitorFunc func(any, any)

type SerializeFunc

type SerializeFunc func(any, any) (any, error)

type Simple

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

func (*Simple) Decrement

func (c *Simple) Decrement(k any, n int64) error

Decrement 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 (*Simple) DecrementFloat

func (c *Simple) DecrementFloat(k any, n float64) error

Decrement an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to decrement it by n. Pass a negative number to decrement the value. To retrieve the decremented value, use one of the specialized methods, e.g. DecrementFloat64.

func (*Simple) DecrementFloat32

func (c *Simple) DecrementFloat32(k any, n float32) (float32, error)

Decrement an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementFloat64

func (c *Simple) DecrementFloat64(k any, n float64) (float64, error)

Decrement an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementInt

func (c *Simple) DecrementInt(k any, n int) (int, error)

Decrement an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementInt32

func (c *Simple) DecrementInt32(k any, n int32) (int32, error)

Decrement 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 decremented value is returned.

func (*Simple) DecrementInt64

func (c *Simple) DecrementInt64(k any, n int64) (int64, error)

Decrement an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementUint

func (c *Simple) DecrementUint(k any, n uint) (uint, error)

Decrement an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementUint32

func (c *Simple) DecrementUint32(k any, n uint32) (uint32, error)

Decrement an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementUint64

func (c *Simple) DecrementUint64(k any, n uint64) (uint64, error)

Decrement an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) DecrementUintptr

func (c *Simple) DecrementUintptr(k any, n uintptr) (uintptr, error)

Decrement an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the decremented value is returned.

func (*Simple) Flush

func (c *Simple) Flush()

Remove all items from the Simple.

func (*Simple) Get

func (c *Simple) Get(k any) (any, error)

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

func (*Simple) GetALL

func (c *Simple) GetALL(checkExpired bool) map[any]any

GetALL returns all key-value pairs in the Simple.

func (*Simple) GetWithExpiration

func (c *Simple) GetWithExpiration(k any) (any, time.Time, error)

GetWithExpiration returns an item and its expiration time from the Simple. 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 (*Simple) Has

func (c *Simple) Has(key any) bool

Has checks if key exists in Simple

func (*Simple) Increment

func (c *Simple) Increment(k any, n int64) error

Increment 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.

func (*Simple) IncrementFloat

func (c *Simple) IncrementFloat(k any, n float64) error

Increment an item of type float32 or float64 by n. Returns an error if the item's value is not floating point, if it was not found, or if it is not possible to increment it by n. Pass a negative number to decrement the value. To retrieve the incremented value, use one of the specialized methods, e.g. IncrementFloat64.

func (*Simple) IncrementFloat32

func (c *Simple) IncrementFloat32(k any, n float32) (float32, error)

Increment an item of type float32 by n. Returns an error if the item's value is not an float32, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementFloat64

func (c *Simple) IncrementFloat64(k any, n float64) (float64, error)

Increment an item of type float64 by n. Returns an error if the item's value is not an float64, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementInt

func (c *Simple) IncrementInt(k any, n int) (int, error)

Increment an item of type int by n. Returns an error if the item's value is not an int, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementInt32

func (c *Simple) IncrementInt32(k any, n int32) (int32, 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.

func (*Simple) IncrementInt64

func (c *Simple) IncrementInt64(k any, n int64) (int64, error)

Increment an item of type int64 by n. Returns an error if the item's value is not an int64, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementUint

func (c *Simple) IncrementUint(k any, n uint) (uint, error)

Increment an item of type uint by n. Returns an error if the item's value is not an uint, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementUint32

func (c *Simple) IncrementUint32(k any, n uint32) (uint32, error)

Increment an item of type uint32 by n. Returns an error if the item's value is not an uint32, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementUint64

func (c *Simple) IncrementUint64(k any, n uint64) (uint64, error)

Increment an item of type uint64 by n. Returns an error if the item's value is not an uint64, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) IncrementUintptr

func (c *Simple) IncrementUintptr(k any, n uintptr) (uintptr, error)

Increment an item of type uintptr by n. Returns an error if the item's value is not an uintptr, or if it was not found. If there is no error, the incremented value is returned.

func (*Simple) Items

func (c *Simple) Items() map[any]item

Copies all unexpired items in the Simple into a new map and returns it.

func (*Simple) Keys

func (c *Simple) Keys(checkExpired bool) []any

Keys returns a slice of the keys in the Simple.

func (*Simple) Len

func (c *Simple) Len(checkExpired bool) int

Len returns the number of items in the Simple.

func (*Simple) Load

func (c *Simple) Load(r io.Reader) error

SetNX (Gob-serialized) Simple items from an io.Reader, excluding any items with keys that already exist (and haven't expired) in the current Simple.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Simple) LoadFile

func (c *Simple) LoadFile(fname string) error

Load and add Simple items from the given filename, excluding any items with keys that already exist in the current Simple.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Simple) OnEvicted

func (c *Simple) OnEvicted(f func(any, any))

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

func (*Simple) Purge

func (c *Simple) Purge()

Purge all expired items from the Simple.

func (*Simple) Remove

func (c *Simple) Remove(k any) bool

Remove an item from the Simple. Does nothing if the key is not in the Simple.

func (*Simple) Replace

func (c *Simple) Replace(k any, x any, d time.Duration) error

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

func (*Simple) Save

func (c *Simple) Save(w io.Writer) (err error)

Write the Simple's items (using Gob) to an io.Writer.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Simple) SaveFile

func (c *Simple) SaveFile(fname string) error

Save the Simple's items to the given filename, creating the file if it doesn't exist, and overwriting it if it does.

NOTE: This method is deprecated in favor of c.Items() and NewFrom() (see the documentation for NewFrom().)

func (*Simple) Set

func (c *Simple) Set(k any, x any, d time.Duration) error

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

func (*Simple) SetNX

func (c *Simple) SetNX(k any, x any, d time.Duration) error

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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