gcache

package
v0.3.25 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2026 License: MIT Imports: 7 Imported by: 0

README

GCache

Test GoDoc

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 any) (any, 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 any) (any, *time.Duration, error) {
      loaderCounter++
      expire := 1 * time.Second
      return "ok", &expire, nil
    }).
    EvictedFunc(func(key, value any) {
      evictCounter++
      fmt.Println("evicted key:", key)
    }).
    PurgeVisitorFunc(func(key, value any) {
      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 any) (any, 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 any) {
      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 any) {
      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

This section is empty.

Variables

View Source
var ErrKeyNotFoundError = errors.New("key not found")

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

func (c *ARC) EvictType() EvictType

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

func (*ARC) SetWithExpire

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

Set a new key-value pair with an expiration time

type AddedFunc

type AddedFunc func(any, any)

type Cache

type Cache interface {
	EvictType() EvictType
	// Set inserts or updates the specified key-value pair.
	Set(key, value any) error
	// SetWithExpire inserts or updates the specified key-value pair with an expiration time.
	SetWithExpire(key, value any, expiration time.Duration) error
	// Get returns the value for the specified key if it is present in the cache.
	// If the key is not present in the cache and the cache has LoaderFunc,
	// invoke the `LoaderFunc` function and inserts the key-value pair in the cache.
	// If the key is not present in the cache and the cache does not have a LoaderFunc,
	// return KeyNotFoundError.
	Get(key any) (any, error)
	// GetAll returns a map containing all key-value pairs in the cache.
	GetALL(checkExpired bool) map[any]any

	// Remove removes the specified key from the cache if the key is present.
	// Returns true if the key was present and the key has been deleted.
	Remove(key any) bool
	// Purge removes all key-value pairs from the cache.
	Purge()
	// Keys returns a slice containing all keys in the cache.
	Keys(checkExpired bool) []any
	// Len returns the number of items in the cache.
	Len(checkExpired bool) int
	// Has returns true if the key exists in the cache.
	Has(key any) bool
	// 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) Clock

func (cb *CacheBuilder) Clock(clock Clock) *CacheBuilder

func (*CacheBuilder) DeserializeFunc

func (cb *CacheBuilder) DeserializeFunc(deserializeFunc DeserializeFunc) *CacheBuilder

func (*CacheBuilder) EvictType

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

func (*CacheBuilder) EvictedFunc

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

func (*CacheBuilder) Expiration

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

func (*CacheBuilder) LFU

func (cb *CacheBuilder) LFU() *CacheBuilder

func (*CacheBuilder) LRU

func (cb *CacheBuilder) LRU() *CacheBuilder

func (*CacheBuilder) LoaderExpireFunc

func (cb *CacheBuilder) LoaderExpireFunc(loaderExpireFunc LoaderExpireFunc) *CacheBuilder

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

func (*CacheBuilder) LoaderFunc

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

Set a loader function. loaderFunc: create a new value with this function if cached value is expired.

func (*CacheBuilder) PurgeVisitorFunc

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

func (*CacheBuilder) SerializeFunc

func (cb *CacheBuilder) SerializeFunc(serializeFunc SerializeFunc) *CacheBuilder

func (*CacheBuilder) Simple

func (cb *CacheBuilder) Simple() *CacheBuilder

type Clock

type Clock interface {
	Now() time.Time
}

func NewRealClock

func NewRealClock() Clock

type DeserializeFunc

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

type EvictType

type EvictType string
const (
	TYPE_SIMPLE EvictType = "simple"
	TYPE_LRU    EvictType = "lru"
	TYPE_LFU    EvictType = "lfu"
	TYPE_ARC    EvictType = "arc"
)

type EvictedFunc

type EvictedFunc func(any, any)

type FakeClock

type FakeClock interface {
	Clock

	Advance(d time.Duration)
}

func NewFakeClock

func NewFakeClock() FakeClock

type LFUCache

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

Discards the least frequently used items first.

func (*LFUCache) EvictType

func (c *LFUCache) EvictType() EvictType

func (*LFUCache) Get

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

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

func (*LFUCache) GetALL

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

GetALL returns all key-value pairs in the cache.

func (*LFUCache) Has

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

Has checks if key exists in cache

func (*LFUCache) Keys

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

Keys returns a slice of the keys in the cache.

func (*LFUCache) Len

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

Len returns the number of items in the cache.

func (*LFUCache) Purge

func (c *LFUCache) Purge()

Completely clear the cache

func (*LFUCache) Remove

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

Remove removes the provided key from the cache.

func (*LFUCache) Set

func (c *LFUCache) Set(key, value any) error

Set a new key-value pair

func (*LFUCache) SetWithExpire

func (c *LFUCache) SetWithExpire(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

type LRUCache

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

Discards the least recently used items first.

func (*LRUCache) EvictType

func (c *LRUCache) EvictType() EvictType

func (*LRUCache) Get

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

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

func (*LRUCache) GetALL

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

GetALL returns all key-value pairs in the cache.

func (*LRUCache) Has

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

Has checks if key exists in cache

func (*LRUCache) Keys

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

Keys returns a slice of the keys in the cache.

func (*LRUCache) Len

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

Len returns the number of items in the cache.

func (*LRUCache) Purge

func (c *LRUCache) Purge()

Completely clear the cache

func (*LRUCache) Remove

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

Remove removes the provided key from the cache.

func (*LRUCache) Set

func (c *LRUCache) Set(key, value any) error

set a new key-value pair

func (*LRUCache) SetWithExpire

func (c *LRUCache) SetWithExpire(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

type LoaderExpireFunc

type LoaderExpireFunc func(any) (any, *time.Duration, error)

type LoaderFunc

type LoaderFunc func(any) (any, error)

type PurgeVisitorFunc

type PurgeVisitorFunc func(any, any)

type RealClock

type RealClock struct{}

func (RealClock) Now

func (rc RealClock) Now() time.Time

type SerializeFunc

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

type SimpleCache

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

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

func (*SimpleCache) EvictType

func (c *SimpleCache) EvictType() EvictType

func (*SimpleCache) Get

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

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

func (*SimpleCache) GetALL

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

GetALL returns all key-value pairs in the cache.

func (*SimpleCache) Has

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

Has checks if key exists in cache

func (*SimpleCache) Keys

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

Keys returns a slice of the keys in the cache.

func (*SimpleCache) Len

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

Len returns the number of items in the cache.

func (*SimpleCache) Purge

func (c *SimpleCache) Purge()

Completely clear the cache

func (*SimpleCache) Remove

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

Remove removes the provided key from the cache.

func (*SimpleCache) Set

func (c *SimpleCache) Set(key, value any) error

Set a new key-value pair

func (*SimpleCache) SetWithExpire

func (c *SimpleCache) SetWithExpire(key, value any, expiration time.Duration) error

Set a new key-value pair with an expiration time

Directories

Path Synopsis
examples
autoloading command

Jump to

Keyboard shortcuts

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