缓存服务
2 分钟阅读
简要概述
支持 memory、redis 实现数据临时缓存,以降低查询后端数据库压力。
配置示例
最小化配置
# 缓存服务配置
cachebox:
enable: true
driver: memory
memory:
max_entry: 60
导出默认值
# 缓存服务配置
cachebox:
enable: true
driver: redis # memory, redis
memory:
max_entry: 1024
redis:
endpoints:
- 127.0.0.1:6380
- 127.0.0.1:6381
- 127.0.0.1:6382
username: ""
password: ""
db_number: 1
sentinel:
master_name: ""
username: ""
password: ""
tls_client_config:
ca_file: ""
cert_file: ""
key_file: ""
insecure_skip_verify: true
函数定义
公共接口
// LRUCachebox 缓存实现 LRU 效果
type LRUCachebox interface {
// Remove 重内存缓存移除值
Remove(ctx context.Context, key string) bool
// SetValue 向内存缓存添加值
SetValue(ctx context.Context, key string, value any) bool
// GetStructValue 从内存缓存获取值,并填充用户给定的类型
GetStructValue(ctx context.Context, key string, ptx any) bool
}
获取实例
// GetLRUCachebox 用于获取 LRU 缓存
func (c *LocalConfig) GetLRUCachebox() (LRUCachebox, error) {
......
}
// GetCacheboxRedisClient 用于获取缓存服务中初始化的 redis 连接
func (c *LocalConfig) GetCacheboxRedisClient() (redis.UniversalClient, error) {
......
}
// HasCacheboxEnabled 用于判断是否启用缓存
func (c *LocalConfig) HasCacheboxEnabled() bool {
......
}
应用场景
使用内存缓存
- app.yaml 配置
# 缓存服务配置
cachebox:
enable: true
driver: memory # memory, redis
memory:
max_entry: 60
- 获取实例
// 判断配置中是否开启缓存
if m.baseCfg.HasCacheboxEnabled() {
lruCache, err := m.baseCfg.GetLRUCachebox()
if err == nil && lruCache != nil {
if lruCache.SetValue(ctx, cacheKey, u) {
m.logger.Debugf("set cache success success")
}
}
}
使用单实例 redis 缓存
- app.yaml 配置
# 缓存服务配置
cachebox:
enable: true
driver: redis
redis:
endpoints:
- 127.0.0.1:6379
db_number: 0
- 获取实例
同上。
使用 redis cluster 缓存
- app.yaml 配置
# 缓存服务配置
cachebox:
enable: true
driver: redis
redis:
endpoints:
- 127.0.0.1:6380
- 127.0.0.1:6381
- 127.0.0.1:6382
username: ""
password: ""
- 获取实例
同上。
使用 redis sentinel 缓存
- app.yaml 配置
# 缓存服务配置
cachebox:
enable: true
driver: redis
redis:
endpoints:
- 127.0.0.1:6380
- 127.0.0.1:6381
- 127.0.0.1:6382
sentinel:
master_name: "test"
username: ""
password: ""
- 获取实例
同上。
最后修改 December 2, 2024: docs: add redis sentinel (d5df627)