Cache
Cache library with Redis backend for Golang
Install / Use
/learn @go-redis/CacheREADME
Redis cache library for Golang
go-redis/cache is brought to you by :star: uptrace/uptrace. Uptrace is an open source and blazingly fast distributed tracing tool powered by OpenTelemetry and ClickHouse. Give it a star as well!
go-redis/cache library implements a cache using Redis as a key/value storage. It uses MessagePack to marshal values.
Optionally, you can use TinyLFU or any other cache algorithm as a local in-process cache.
If you are interested in monitoring cache hit rate, see the guide for Monitoring using OpenTelemetry Metrics.
Installation
go-redis/cache supports 2 last Go versions and requires a Go version with modules support. So make sure to initialize a Go module:
go mod init github.com/my/repo
And then install go-redis/cache/v9 (note v9 in the import; omitting it is a popular mistake):
go get github.com/go-redis/cache/v9
Quickstart
package cache_test
import (
"context"
"fmt"
"time"
"github.com/redis/go-redis/v9"
"github.com/go-redis/cache/v9"
)
type Object struct {
Str string
Num int
}
func Example_basicUsage() {
ring := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"server1": ":6379",
"server2": ":6380",
},
})
mycache := cache.New(&cache.Options{
Redis: ring,
LocalCache: cache.NewTinyLFU(1000, time.Minute),
})
ctx := context.TODO()
key := "mykey"
obj := &Object{
Str: "mystring",
Num: 42,
}
if err := mycache.Set(&cache.Item{
Ctx: ctx,
Key: key,
Value: obj,
TTL: time.Hour,
}); err != nil {
panic(err)
}
var wanted Object
if err := mycache.Get(ctx, key, &wanted); err == nil {
fmt.Println(wanted)
}
// Output: {mystring 42}
}
func Example_advancedUsage() {
ring := redis.NewRing(&redis.RingOptions{
Addrs: map[string]string{
"server1": ":6379",
"server2": ":6380",
},
})
mycache := cache.New(&cache.Options{
Redis: ring,
LocalCache: cache.NewTinyLFU(1000, time.Minute),
})
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)
}
fmt.Println(obj)
// Output: &{mystring 42}
}
Related Skills
node-connect
353.1kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
xurl
353.1kA CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.
frontend-design
111.6kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
353.1kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
