缓存服务
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: ""
server_name: ""
min_version: ""
max_version: ""
insecure_skip_verify: true
以上为示例值而非默认值。代码内的实际缺省行为:
enable缺省为 false (不启用缓存);driver无默认值,启用后必填(否则报cachebox driver not found);memory.max_entry为 0 时不限制条目数;insecure_skip_verify零值为 false。
函数定义
公共接口
// LRUCachebox 缓存实现 LRU 效果
type LRUCachebox interface {
// Remove 重内存缓存移除值
Remove(ctx context.Context, key string) bool
// SetValue 向内存缓存添加值
SetValue(ctx context.Context, key string, value any) bool
// SetValueWithTTL 向内存缓存添加值,并指定存活时间
SetValueWithTTL(ctx context.Context, key string, value any, ttl time.Duration) 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.DebugContext(ctx, "set cache 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: ""
- 获取实例
同上。