Golang Redis 缓存
Redis 配置
要开始使用 Redis 作为缓存存储,请使用以下 Redis 配置
# Required
##########
# Set a memory usage limit to the specified amount of bytes.
# When the memory limit is reached Redis will try to remove keys
# according to the eviction policy selected (see maxmemory-policy).
maxmemory 100mb
# Optional
##########
# Evict any key using approximated LFU when maxmemory is reached.
maxmemory-policy allkeys-lfu
# Enable active memory defragmentation.
activedefrag yes
# Don't save data on the disk because we can afford to lose cached data.
save ""
go-redis/cache
go-redis/cache 库使用 Redis 作为键值存储实现缓存。它使用 MessagePack 对值进行编组。
您可以使用以下命令安装 go-redis/cache
go get github.com/go-redis/cache/v8
go-redis/cache 接受一个接口来与 Redis 通信,因此支持 go-redis 提供的所有类型的 Redis 客户端。
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)
}
您还可以使用本地进程内存储来缓存一小部分热门键。go-redis/cache 附带了 TinyLFU,但您可以使用任何其他 缓存算法,它实现了该接口。
mycache := cache.New(&cache.Options{
Redis: rdb,
// Cache 10k keys for 1 minute.
LocalCache: cache.NewTinyLFU(10000, time.Minute),
})
缓存监控
如果您有兴趣监控缓存命中率,请参阅使用 OpenTelemetry 指标监控 的指南。
监控性能
监控 Redis 数据库的性能对于维护系统的整体运行状况、效率和可靠性至关重要。适当的性能监控有助于在潜在问题导致服务中断或性能下降之前识别和解决这些问题。
Uptrace 是一个 Grafana 替代品,它支持分布式跟踪、指标和日志。您可以使用它来监控应用程序并排查问题。
Uptrace 带有一个直观的查询生成器、丰富的仪表盘、带有通知的警报规则以及大多数语言和框架的集成。
Uptrace 可以在单个服务器上处理数十亿个跨度和指标,并允许您以低 10 倍的成本监控您的应用程序。
只需几分钟,您就可以通过访问 云演示 (无需登录)或使用 Docker 在本地运行它。源代码可在 GitHub 上获得。