In-memory cache with expiration and eviction.
A thread-safe in-memory cache implementation.
Memory is an expensive resource, so an implementation of clearing obsolete records is provided, as well as an implementation of expelling records when the specified limit is reached.
Set CleanupInterval
to enable obsolete records clearing.
Set LimitEntries
to enable records expelling when count limit is reached.
Obsolete records are evicted first, then record are expelled by durability and FIFO method.
Special thanks to ks-troyan.
go get github.com/a-projects/go-memorycache@latest
import (
"fmt"
"time"
"github.com/a-projects/go-memorycache"
)
func main() {
// create cache instance
cache := memorycache.New(memorycache.MemoryCacheOptions{
// periodic records clearing, every 15 min
// if not set, then it does not start
CleanupInterval: time.Minute * 15,
// cache entries limit, recods
// if not set, then unlimited
LimitEntries: 65_536,
// file used to restore data from disc when app is restarted
// if not set, it does not restore
FileName: "cache.bin",
})
// retrieve an item from cache by key "foo"
res, ok := cache.Get("foo")
// if item with given key are not found
// reasons:
// - entry was never stored in cache
// - entry was stored, but expired
// - entry was stored, but was removed from cache
// - entry was stored, but was expelled
if !ok {
// retrieving item from external sources
res = "bar"
// add entry to cache as a key value pair
cache.Set("foo", res, memorycache.MemoryCacheEntryOptions{
// set lifetime
// if not set, then not stored
Lifetime: time.Minute * 5,
// set expellence resistence
// if not set, then Normal
Durability: memorycache.Normal,
})
}
// cast result and print to console
fmt.Printf(res.(string))
// close cache instance, all chache data will be writen to FileName file
cache.Close()
}