☔️ A complete Go cache library that brings you multiple ways of managing your caches
☔️ A complete Go cache library that brings you multiple ways of managing your caches
Guess what is Gocache? a Go cache library. This is an extendable cache library that brings you a lot of features for caching data.
Here is what it brings in detail:
Stores do not all accept the same value types, and not all of them provide every operation. Keys are always strings (Ristretto excepted, where the key type is a generic parameter).
| Store | Values accepted by Set() |
Values returned by Get() |
Per-key expiration | Tags | SetIfNotExists() |
|---|---|---|---|---|---|
| Bigcache | string, []byte |
[]byte |
no, client-wide | yes | no |
| Freecache | []byte |
[]byte |
yes | yes | no |
| Go-cache | any | as stored | yes | yes | yes |
| Hazelcast | any serializable by the client | as stored | yes | yes | no |
| Memcache | []byte |
[]byte |
yes | yes | yes |
| Pegasus | anything cast.ToString handles |
[]byte |
yes | yes | no |
| Redis | anything go-redis can marshal | string |
yes | yes | yes |
| Redis cluster | anything go-redis can marshal | string |
yes | yes | yes |
| Ristretto | the store value type V |
V |
yes | yes¹ | no |
| Rueidis | string, []byte |
string |
yes | yes | no |
| Valkey | string, []byte |
string |
yes | yes | no |
¹ Ristretto tags need string keys and a value type able to hold the tag list (string, []byte or any).
cache.Cache converts between string and []byte for you, so cache.New[string](bigcacheStore) and
cache.New[[]byte](redisStore) both work. To store anything else in a store that only handles bytes, use the
marshaler wrapper.
Two more things worth knowing:
GetWithTTL() reports a fixed 5 minutes in order to stay usable in a Chain cache,Set() when its buffers are full — this is by design in
its FAQ — in which case Set() returns an error. Use
store.WithSynchronousSet() if you need the write to be visible right after the call.To begin working with the latest version of gocache, you can import the library in your project:
go get github.com/eko/gocache/lib/v4and then, import the store(s) you want to use between all available ones:
go get github.com/eko/gocache/store/bigcache/v4
go get github.com/eko/gocache/store/freecache/v4
go get github.com/eko/gocache/store/go_cache/v4
go get github.com/eko/gocache/store/hazelcast/v4
go get github.com/eko/gocache/store/memcache/v4
go get github.com/eko/gocache/store/pegasus/v4
go get github.com/eko/gocache/store/redis/v4
go get github.com/eko/gocache/store/rediscluster/v4
go get github.com/eko/gocache/store/rueidis/v4
go get github.com/eko/gocache/store/ristretto/v4
go get github.com/eko/gocache/store/valkey/v4Then, simply use the following import statements:
import (
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/store/redis/v4"
)If you run into any errors, please be sure to run go mod tidy to clean your go.mod file.
Here is a simple cache instantiation with Redis but you can also look at other available stores:
memcacheStore := memcache_store.NewMemcache(
memcache.New("10.0.0.1:11211", "10.0.0.2:11211", "10.0.0.3:11212"),
store.WithExpiration(10*time.Second),
)
cacheManager := cache.New[[]byte](memcacheStore)
err := cacheManager.Set(ctx, "my-key", []byte("my-value"),
store.WithExpiration(15*time.Second), // Override default value of 10 seconds defined in the store
)
if err != nil {
panic(err)
}
value := cacheManager.Get(ctx, "my-key")
cacheManager.Delete(ctx, "my-key")
cacheManager.Clear(ctx) // Clears the entire cache, in case you want to flush all cachebigcacheClient, _ := bigcache.NewBigCache(bigcache.DefaultConfig(5 * time.Minute))
bigcacheStore := bigcache_store.NewBigcache(bigcacheClient)
cacheManager := cache.New[[]byte](bigcacheStore)
err := cacheManager.Set(ctx, "my-key", []byte("my-value"))
if err != nil {
panic(err)
}
value := cacheManager.Get(ctx, "my-key")…Note that since store/ristretto/v4.3.1, this store is built on top of github.com/dgraph-io/ristretto/v2, whose NewCache takes the key and value types as generic parameters. Upgrading requires updating both the import path and the ristretto.Config instantiation.
gocacheClient := gocache.New(5*time.Minute, 10*time.Minute)
gocacheStore := gocache_store.NewGoCache(gocacheClient)
cacheManager := cache.New[[]byte](gocacheStore)
err := cacheManager.Set(ctx, "my-key", []byte("my-value"))
if err != nil {
panic(err)
}
value, err := cacheManager.Get(ctx, "my-key")
if err != nil {
panic(err)
}
fmt.Printf("%s", value)…NewRedis() takes any client satisfying its RedisClientInterface, which redis.UniversalClient does: the
same store works against a single node, a Sentinel setup or a cluster, without changing anything but the
client options.
redisStore := redis_store.NewRedis(redis.NewUniversalClient(&redis.UniversalOptions{
Addrs: []string{"127.0.0.1:6379", "127.0.0.1:6380"},
}))……Client-side caching is enabled by default with a 10 seconds expiration, use store.WithClientSideCaching() to change it.
freecacheStore := freecache_store.NewFreecache(freecache.NewCache(1000), store.WithExpiration(10 * time.Second))
cacheManager := cache.New[[]byte](freecacheStore)
err := cacheManager.Set(ctx, "by-key", []byte("my-value"), opts)
if err != nil {
panic(err)
}
value := cacheManager.Get(ctx, "my-key")[!WARNING] This store is deprecated and will be removed in the next major version. It is built on XiaoMi/pegasus-go-client, which has been archived upstream since May 2022 and pulls in unmaintained dependencies. Migrating to apache/incubator-pegasus is blocked: that module has no tagged release and its admin API has changed. It keeps working and existing versions stay available, but it is no longer developed — see #221 if you want to take it over.
pegasusStore, err := pegasus_store.NewPegasus(ctx, &pegasus_store.OptionsPegasus{
MetaServers: []string{"127.0.0.1:34601", "127.0.0.1:34602", "127.0.0.1:34603"},
})
if err != nil {
fmt.Println(err)
return
}
cacheManager := cache.New[string](pegasusStore)
err = cacheManager.Set(ctx, "my-key", "my-value", store.WithExpiration(10 * time.Second))
if err != nil {
panic(err)
}
value, _ := cacheManager.Get(ctx, "my-key")…Here, we will chain caches in the following order: first in memory with Ristretto store, then in Redis (as a fallback):
…Chain cache also put data back in previous caches when it's found so in this case, if ristretto doesn't have the data in its cache but redis have, data will also get setted back into ristretto (memory) cache.
This is done in the background, which is why a Chain cache owns a goroutine: call Close() when you don't need it anymore to release it and set the values that are still pending. If your chain lives for the whole lifetime of your process, you don't have to bother.
This cache will provide a load function that acts as a callable function and will set your data back in your cache in case they are not available:
…Note that the cache type has to be one the store actually handles: Redis cannot store a *Book as is, hence
the marshaling above. Have a look at the table of what each store supports.
As for the Chain cache, loaded values are stored in the cache in the background: call Close() when you don't need the cache anymore to release the goroutine that does it and store the values that are still pending.
Of course, you can also pass a Chain cache into the Loadable one so if your data is not available in all caches, it will bring it back in all caches.
This cache will record metrics depending on the metric provider you pass to it. Here we give a Prometheus provider:
// Initialize Redis client and store
redisClient := redis.NewClient(&redis.Options{Addr: "127.0.0.1:6379"})
redisStore := redis_store.NewRedis(redisClient)
// Initializes Prometheus metrics service
promMetrics := metrics.NewPrometheus("my-test-app")
// Initialize metric cache
cacheManager := cache.NewMetric[any](
promMetrics,
cache.New[any](redisStore),
)
// ... Then, you can get your data and metrics will be observed by PrometheusSome caches like Redis stores and returns the value as a string so you have to marshal/unmarshal your structs if you want to cache an object. That's why we bring a marshaler service that wraps your cache and make the work for you:
…The only thing you have to do is to specify the struct in which you want your value to be un
No open issues yet, or sync has not completed.