Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
G

gocache

> 数据库
Open source

☔️ A complete Go cache library that brings you multiple ways of managing your caches

2.9K stars0 likes1 views
WebsiteGitHub

About

☔️ A complete Go cache library that brings you multiple ways of managing your caches

Gocache

Guess what is Gocache? a Go cache library. This is an extendable cache library that brings you a lot of features for caching data.

Overview

Here is what it brings in detail:

  • ✅ Multiple cache stores: actually in memory, redis, or your own custom store
  • ✅ A chain cache: use multiple cache with a priority order (memory then fallback to a redis shared cache for instance)
  • ✅ A loadable cache: allow you to call a callback function to put your data back in cache
  • ✅ A metric cache to let you store metrics about your caches usage (hits, miss, set success, set error, ...)
  • ✅ A marshaler to automatically marshal/unmarshal your cache values as a struct
  • ✅ Define default values in stores and override them when setting data
  • ✅ Cache invalidation by expiration time and/or using tags
  • ✅ Use of Generics

Built-in stores

  • Memory (bigcache) (allegro/bigcache)
  • Memory (ristretto) (dgraph-io/ristretto)
  • Memory (go-cache) (patrickmn/go-cache)
  • Memcache (bradfitz/memcache)
  • Redis (go-redis/redis)
  • Redis (rueidis) (redis/rueidis)
  • Valkey (valkey-io/valkey-go)
  • Freecache (coocood/freecache)
  • Pegasus (apache/incubator-pegasus) benchmark — deprecated, see below
  • Hazelcast (hazelcast-go-client/hazelcast)
  • More to come soon

What each store supports

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:

  • Bigcache has no per-key TTL, so GetWithTTL() reports a fixed 5 minutes in order to stay usable in a Chain cache,
  • Ristretto is allowed to drop a 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.

Built-in metrics providers

  • Prometheus

Installation

To begin working with the latest version of gocache, you can import the library in your project:

go
go get github.com/eko/gocache/lib/v4

and then, import the store(s) you want to use between all available ones:

go
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/v4

Then, simply use the following import statements:

go
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.

Available cache features in detail

A simple cache

Here is a simple cache instantiation with Redis but you can also look at other available stores:

Memcache

go
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 cache

Memory (using Bigcache)

go
bigcacheClient, _ := 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")

Memory (using Ristretto)

…

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.

Memory (using Go-cache)

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

Redis

…

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.

go
redisStore := redis_store.NewRedis(redis.NewUniversalClient(&redis.UniversalOptions{
	Addrs: []string{"127.0.0.1:6379", "127.0.0.1:6380"},
}))

Redis Client-Side Caching (using rueidis)

…

Valkey

…

Client-side caching is enabled by default with a 10 seconds expiration, use store.WithClientSideCaching() to change it.

Freecache

go
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")

Pegasus

[!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.

go
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")

Hazelcast

…

A chained cache

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.

A loadable cache

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.

A metric cache to retrieve cache statistics

This cache will record metrics depending on the metric provider you pass to it. Here we give a Prometheus provider:

go
// 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 Prometheus

A marshaler wrapper

Some 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

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gobigcachecachechaingo

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category数据库
PricingOpen source

> Related tools

P
PostgreSQL
功能强大的开源关系型数据库
R
Redis
内存数据结构存储,常用作缓存与队列
M
MySQL
广泛使用的开源关系型数据库