cache

package
v1.7.8 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT, Apache-2.0, MIT Imports: 7 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.

type AddedFunc

type AddedFunc func(any, any)

type Cache

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

func (*Cache) Clear added in v1.7.8

func (c *Cache) Clear()

Clear is used to completely clear the cache

func (*Cache) Decrement added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementFloat added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementFloat32 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementFloat64 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementInt added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementInt32 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementInt64 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementUint added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementUint32 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementUint64 added in v1.7.8

func (c *Cache) 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 (*Cache) DecrementUintptr added in v1.7.8

func (c *Cache) 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 (*Cache) Get

func (c *Cache) 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 (*Cache) GetALL

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

GetALL returns all key-value pairs in the cache.

func (*Cache) GetIFPresent added in v1.7.8

func (c *Cache) 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 (*Cache) GetWithExpiration added in v1.7.8

func (c *Cache) GetWithExpiration(key any) (any, time.Duration, error)

func (*Cache) Has

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

Has checks if key exists in cache

func (*Cache) Increment added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementFloat added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementFloat32 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementFloat64 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementInt added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementInt32 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementInt64 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementUint added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementUint32 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementUint64 added in v1.7.8

func (c *Cache) 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 (*Cache) IncrementUintptr added in v1.7.8

func (c *Cache) 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 (*Cache) Keys

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

Keys returns a slice of the keys in the cache.

func (*Cache) Len

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

Len returns the number of items in the cache.

func (*Cache) Purge

func (c *Cache) Purge()

Purge is used to completely clear the cache

func (*Cache) Remove

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

Remove removes the provided key from the cache.

func (*Cache) Set

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

Set a new key-value pair with an expiration time

func (*Cache) SetNX

func (c *Cache) SetNX(k any, x any, expiration time.Duration) error

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

type CacheBuilder

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

func New

func New(size int) *CacheBuilder

func (*CacheBuilder) ARC

func (cb *CacheBuilder) ARC() *Cache

func (*CacheBuilder) AddedFunc

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

func (*CacheBuilder) ClearVisitorFunc added in v1.7.8

func (cb *CacheBuilder) ClearVisitorFunc(purgeVisitorFunc ClearVisitorFunc) *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() *Cache

func (*CacheBuilder) LRU

func (cb *CacheBuilder) LRU() *Cache

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) Simple

func (cb *CacheBuilder) Simple() *Cache

type ClearVisitorFunc added in v1.7.8

type ClearVisitorFunc func(any, any)

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.

type LRU

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

Discards the least recently used items first.

type LoaderFunc

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

type SerializeFunc

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

type Simple

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

type Store added in v1.7.8

type Store interface {
	// contains filtered or unexported methods
}

Jump to

Keyboard shortcuts

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