High performance, simple generic cache written in GO, including a
loadingcache.
go get github.com/larscom/go-cacheYou can import go-cache using:
import (
"github.com/larscom/go-cache"
)Create a new loading cache with
inttype as key andstringtype as value.
A common use case for this loading cache would be to automatically fetch data from a REST API and store it in cache. This implementation will ensure that the REST API is only called once in a concurrent environment.
func main() {
loaderFunc := func(key int) (string, error) {
// you may want to call your REST API here...
return "Hello World", nil
}
c := cache.NewLoadingCache[int, string](loaderFunc)
defer c.Close()
value, err := c.Load(1)
if err != nil {
log.Fatal(err)
}
log.Println(value) // Hello World
}With TTL option
Create a new loading cache with time to live of 10 seconds.
This allows you to call Load() as many times as you want and whenever an entry expires it'll call the loaderFunc once.
func main() {
c := cache.NewLoadingCache(loaderFunc, cache.WithExpireAfterWrite[int, string](time.Second * 10))
defer c.Close()
}Create a
regularcache (withoutLoadandReloadfunctions) withTTL
func main() {
c := cache.NewCache[int, string](cache.WithExpireAfterWrite[int, string](time.Second * 10))
defer c.Close()
c.Put(1, "Hello World")
value, found := c.Get(1)
if found {
log.Println(value) // Hello World
}
}