gcache

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2022 License: GPL-3.0 Imports: 6 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 https://github.com/Zeb-D/go-util

Example

Manually set a key-value pair.
package main

import (
	gcache "github.com/Zeb-D/go-util/cache"
    "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 (
	gcache "github.com/Zeb-D/go-util/cache"
  "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 (
	gcache "github.com/Zeb-D/go-util/cache"
  "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"

	gcache "github.com/Zeb-D/go-util/cache"
)

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

Documentation

Index

Constants

View Source
const (
	TypeSimple = "simple"
	TypeLru    = "lru"
	TypeLfu    = "lfu"
	TypeArc    = "arc"
)

Variables

View Source
var KeyNotFoundError = errors.New("Key Not Found.")

Functions

This section is empty.

Types

type ARC added in v1.0.5

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

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

func (*ARC) Get added in v1.0.5

func (c *ARC) Get(key interface{}) (interface{}, 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 added in v1.0.5

func (c *ARC) GetALL(checkExpired bool) map[interface{}]interface{}

GetALL returns all key-value pairs in the cache.

func (*ARC) GetIFPresent added in v1.0.5

func (c *ARC) GetIFPresent(key interface{}) (interface{}, error)

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

func (*ARC) Has added in v1.0.5

func (c *ARC) Has(key interface{}) bool

Has checks if key exists in cache

func (*ARC) Keys added in v1.0.5

func (c *ARC) Keys(checkExpired bool) []interface{}

Keys returns a slice of the keys in the cache.

func (*ARC) Len added in v1.0.5

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

Len returns the number of items in the cache.

func (*ARC) Purge added in v1.0.5

func (c *ARC) Purge()

Purge is used to completely clear the cache

func (*ARC) Remove added in v1.0.5

func (c *ARC) Remove(key interface{}) bool

Remove removes the provided key from the cache.

func (*ARC) Set added in v1.0.5

func (c *ARC) Set(key, value interface{}) error

func (*ARC) SetWithExpire added in v1.0.5

func (c *ARC) SetWithExpire(key, value interface{}, expiration time.Duration) error

SetWithExpire a new key-value pair with an expiration time

type AddedFunc added in v1.0.5

type AddedFunc func(interface{}, interface{})

type Cache

type Cache interface {
	// Set inserts or updates the specified key-value pair.
	Set(key, value interface{}) error
	// SetWithExpire inserts or updates the specified key-value pair with an expiration time.
	SetWithExpire(key, value interface{}, 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 interface{}) (interface{}, error)
	// GetIFPresent returns the value for the specified key if it is present in the cache.
	// Return KeyNotFoundError if the key is not present.
	GetIFPresent(key interface{}) (interface{}, error)
	// GetALL returns a map containing all key-value pairs in the cache.
	// Return all inExpired kv
	GetALL(checkExpired bool) map[interface{}]interface{}

	// 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 interface{}) bool
	// Purge removes all key-value pairs from the cache.
	Purge()
	// Keys returns a slice containing all keys in the cache.
	Keys(checkExpired bool) []interface{}
	// 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 interface{}) bool
	// contains filtered or unexported methods
}

type CacheBuilder added in v1.0.5

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

func New added in v1.0.5

func New(size int) *CacheBuilder

func (*CacheBuilder) ARC added in v1.0.5

func (cb *CacheBuilder) ARC() *CacheBuilder

func (*CacheBuilder) AddedFunc added in v1.0.5

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

func (*CacheBuilder) Build added in v1.0.5

func (cb *CacheBuilder) Build() Cache

func (*CacheBuilder) Clock added in v1.0.5

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

func (*CacheBuilder) DeserializeFunc added in v1.0.5

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

func (*CacheBuilder) EvictType added in v1.0.5

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

func (*CacheBuilder) EvictedFunc added in v1.0.5

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

func (*CacheBuilder) Expiration added in v1.0.5

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

func (*CacheBuilder) LFU added in v1.0.5

func (cb *CacheBuilder) LFU() *CacheBuilder

func (*CacheBuilder) LRU added in v1.0.5

func (cb *CacheBuilder) LRU() *CacheBuilder

func (*CacheBuilder) LoaderExpireFunc added in v1.0.5

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

LoaderExpireFunc 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 added in v1.0.5

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

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

func (*CacheBuilder) PurgeVisitorFunc added in v1.0.5

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

func (*CacheBuilder) SerializeFunc added in v1.0.5

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

func (*CacheBuilder) Simple added in v1.0.5

func (cb *CacheBuilder) Simple() *CacheBuilder

type Clock added in v1.0.5

type Clock interface {
	Now() time.Time
}

func NewRealClock added in v1.0.5

func NewRealClock() Clock

type DeserializeFunc added in v1.0.5

type DeserializeFunc func(interface{}, interface{}) (interface{}, error)

type EvictedFunc added in v1.0.5

type EvictedFunc func(interface{}, interface{})

type FakeClock added in v1.0.5

type FakeClock interface {
	Clock

	Advance(d time.Duration)
}

func NewFakeClock added in v1.0.5

func NewFakeClock() FakeClock

type Group added in v1.0.5

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 added in v1.0.5

func (g *Group) Do(key interface{}, fn func() (interface{}, error), isWait bool) (interface{}, 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 LFUCache added in v1.0.5

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

LFUCache Discards the least frequently used items first.

func (*LFUCache) Get added in v1.0.5

func (c *LFUCache) Get(key interface{}) (interface{}, 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 added in v1.0.5

func (c *LFUCache) GetALL(checkExpired bool) map[interface{}]interface{}

GetALL returns all key-value pairs in the cache.

func (*LFUCache) GetIFPresent added in v1.0.5

func (c *LFUCache) GetIFPresent(key interface{}) (interface{}, error)

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

func (*LFUCache) Has added in v1.0.5

func (c *LFUCache) Has(key interface{}) bool

Has checks if key exists in cache

func (*LFUCache) Keys added in v1.0.5

func (c *LFUCache) Keys(checkExpired bool) []interface{}

Keys returns a slice of the keys in the cache.

func (*LFUCache) Len added in v1.0.5

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

Len returns the number of items in the cache.

func (*LFUCache) Purge added in v1.0.5

func (c *LFUCache) Purge()

Completely clear the cache

func (*LFUCache) Remove added in v1.0.5

func (c *LFUCache) Remove(key interface{}) bool

Remove removes the provided key from the cache.

func (*LFUCache) Set added in v1.0.5

func (c *LFUCache) Set(key, value interface{}) error

Set a new key-value pair

func (*LFUCache) SetWithExpire added in v1.0.5

func (c *LFUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error

SetWithExpire a new key-value pair with an expiration time

type LRUCache added in v1.0.5

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

LRUCache Discards the least recently used items first.

func (*LRUCache) Get added in v1.0.5

func (c *LRUCache) Get(key interface{}) (interface{}, 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 added in v1.0.5

func (c *LRUCache) GetALL(checkExpired bool) map[interface{}]interface{}

GetALL returns all key-value pairs in the cache.

func (*LRUCache) GetIFPresent added in v1.0.5

func (c *LRUCache) GetIFPresent(key interface{}) (interface{}, error)

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

func (*LRUCache) Has added in v1.0.5

func (c *LRUCache) Has(key interface{}) bool

Has checks if key exists in cache

func (*LRUCache) Keys added in v1.0.5

func (c *LRUCache) Keys(checkExpired bool) []interface{}

Keys returns a slice of the keys in the cache.

func (*LRUCache) Len added in v1.0.5

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

Len returns the number of items in the cache.

func (*LRUCache) Purge added in v1.0.5

func (c *LRUCache) Purge()

Completely clear the cache

func (*LRUCache) Remove added in v1.0.5

func (c *LRUCache) Remove(key interface{}) bool

Remove removes the provided key from the cache.

func (*LRUCache) Set added in v1.0.5

func (c *LRUCache) Set(key, value interface{}) error

Set a new key-value pair

func (*LRUCache) SetWithExpire added in v1.0.5

func (c *LRUCache) SetWithExpire(key, value interface{}, expiration time.Duration) error

SetWithExpire a new key-value pair with an expiration time

type LoaderExpireFunc added in v1.0.5

type LoaderExpireFunc func(interface{}) (interface{}, *time.Duration, error)

type LoaderFunc added in v1.0.5

type LoaderFunc func(interface{}) (interface{}, error)

type PurgeVisitorFunc added in v1.0.5

type PurgeVisitorFunc func(interface{}, interface{})

type RealClock added in v1.0.5

type RealClock struct{}

func (RealClock) Now added in v1.0.5

func (rc RealClock) Now() time.Time

type SerializeFunc added in v1.0.5

type SerializeFunc func(interface{}, interface{}) (interface{}, error)

type SimpleCache added in v1.0.5

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) Get added in v1.0.5

func (c *SimpleCache) Get(key interface{}) (interface{}, 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 added in v1.0.5

func (c *SimpleCache) GetALL(checkExpired bool) map[interface{}]interface{}

GetALL returns all key-value pairs in the cache.

func (*SimpleCache) GetIFPresent added in v1.0.5

func (c *SimpleCache) GetIFPresent(key interface{}) (interface{}, error)

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

func (*SimpleCache) Has added in v1.0.5

func (c *SimpleCache) Has(key interface{}) bool

Has checks if key exists in cache

func (*SimpleCache) Keys added in v1.0.5

func (c *SimpleCache) Keys(checkExpired bool) []interface{}

Keys returns a slice of the keys in the cache.

func (*SimpleCache) Len added in v1.0.5

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

Len returns the number of items in the cache.

func (*SimpleCache) Purge added in v1.0.5

func (c *SimpleCache) Purge()

Completely clear the cache

func (*SimpleCache) Remove added in v1.0.5

func (c *SimpleCache) Remove(key interface{}) bool

Remove removes the provided key from the cache.

func (*SimpleCache) Set added in v1.0.5

func (c *SimpleCache) Set(key, value interface{}) error

Set a new key-value pair

func (*SimpleCache) SetWithExpire added in v1.0.5

func (c *SimpleCache) SetWithExpire(key, value interface{}, expiration time.Duration) error

SetWithExpire a new key-value pair with an expiration time

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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