Caching using Redis

go-redis/cacheopen in new window library implements a cache using Redis as a key/value storage. It uses MessagePackopen in new window to marshal values.

You can install go-redis/cache with:

go get github.com/go-redis/cache/v8

go-redis/cache accepts an interface to communicate with Redis and thus supports all types of Redis clients that go-redis provides.

rdb := redis.NewClient(&redis.Options{
    Addr: "localhost:6379",
})

mycache := cache.New(&cache.Options{
    Redis: rdb,
})

obj := new(Object)
err := mycache.Once(&cache.Item{
    Key:   "mykey",
    Value: obj, // destination
    Do: func(*cache.Item) (interface{}, error) {
        return &Object{
            Str: "mystring",
            Num: 42,
        }, nil
    },
})
if err != nil {
    panic(err)
}

You can also use local in-process storage to cache the small subset of popular keys. go-redis/cache comes with TinyLFUopen in new window, but you can use any other cache algorithmopen in new window that implements the interface.

mycache := cache.New(&cache.Options{
    Redis:      rdb,
    // Cache 10k keys for 1 minute.
    LocalCache: cache.NewTinyLFU(10000, time.Minute),
})

If you are interested in monitoring cache hit rate, see the guide for Monitoring using OpenTelemetry Metricsopen in new window.