Documentation
¶
Overview ¶
Package cache 提供Redis缓存管理功能 基于 go-redis v9 库提供高性能Redis缓存操作
Package cache 提供Redis缓存工具函数
Index ¶
- Constants
- func ShutdownAllRedisManagers()
- func TryLocker(lockObj string, expSecond int, callObj func(lock *Lock) error, ...) error
- func ValidateLockConfig(config *LockConfig) error
- type Cache
- type CacheManager
- func (self *CacheManager) BatchGet(keys []string) (map[string]interface{}, error)
- func (self *CacheManager) BatchGetToTargets(keys []string, targets []interface{}) error
- func (self *CacheManager) BatchGetToTargetsContext(ctx context.Context, keys []string, targets []interface{}) error
- func (self *CacheManager) BatchGetWithContext(ctx context.Context, keys []string) (map[string]interface{}, error)
- func (self *CacheManager) BatchGetWithDeserializer(keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
- func (self *CacheManager) BatchGetWithDeserializerContext(ctx context.Context, keys []string, ...) (map[string]interface{}, error)
- func (self *CacheManager) Brpop(key string, expire int64, result interface{}) error
- func (self *CacheManager) BrpopBool(key string, expire int64) (bool, error)
- func (self *CacheManager) BrpopBoolWithContext(ctx context.Context, key string, expire int64) (bool, error)
- func (self *CacheManager) BrpopFloat64(key string, expire int64) (float64, error)
- func (self *CacheManager) BrpopFloat64WithContext(ctx context.Context, key string, expire int64) (float64, error)
- func (self *CacheManager) BrpopInt64(key string, expire int64) (int64, error)
- func (self *CacheManager) BrpopInt64WithContext(ctx context.Context, key string, expire int64) (int64, error)
- func (self *CacheManager) BrpopString(key string, expire int64) (string, error)
- func (self *CacheManager) BrpopStringWithContext(ctx context.Context, key string, expire int64) (string, error)
- func (self *CacheManager) BrpopWithContext(ctx context.Context, key string, expire int64, result interface{}) error
- func (self *CacheManager) Del(key ...string) error
- func (self *CacheManager) DelWithContext(ctx context.Context, key ...string) error
- func (self *CacheManager) Exists(key string) (bool, error)
- func (self *CacheManager) ExistsWithContext(ctx context.Context, key string) (bool, error)
- func (self *CacheManager) Flush() error
- func (self *CacheManager) FlushWithContext(ctx context.Context) error
- func (self *CacheManager) Get(key string, input interface{}) (interface{}, bool, error)
- func (self *CacheManager) GetBool(key string) (bool, error)
- func (self *CacheManager) GetBoolWithContext(ctx context.Context, key string) (bool, error)
- func (self *CacheManager) GetBytes(key string) ([]byte, error)
- func (self *CacheManager) GetBytesWithContext(ctx context.Context, key string) ([]byte, error)
- func (self *CacheManager) GetFloat64(key string) (float64, error)
- func (self *CacheManager) GetFloat64WithContext(ctx context.Context, key string) (float64, error)
- func (self *CacheManager) GetInt64(key string) (int64, error)
- func (self *CacheManager) GetInt64WithContext(ctx context.Context, key string) (int64, error)
- func (self *CacheManager) GetString(key string) (string, error)
- func (self *CacheManager) GetStringWithContext(ctx context.Context, key string) (string, error)
- func (self *CacheManager) GetWithContext(ctx context.Context, key string, input interface{}) (interface{}, bool, error)
- func (self *CacheManager) Keys(pattern ...string) ([]string, error)
- func (self *CacheManager) KeysWithContext(ctx context.Context, pattern ...string) ([]string, error)
- func (self *CacheManager) LuaScript(script string, key []string, val ...interface{}) (interface{}, error)
- func (self *CacheManager) LuaScriptWithContext(ctx context.Context, script string, key []string, val ...interface{}) (interface{}, error)
- func (self *CacheManager) Mode() string
- func (self *CacheManager) Publish(key string, val interface{}, try ...int) (bool, error)
- func (self *CacheManager) PublishWithContext(ctx context.Context, key string, val interface{}, try ...int) (bool, error)
- func (self *CacheManager) Put(key string, input interface{}, expire ...int) error
- func (self *CacheManager) PutBatch(objs ...*PutObj) error
- func (self *CacheManager) PutBatchWithContext(ctx context.Context, objs ...*PutObj) error
- func (self *CacheManager) PutWithContext(ctx context.Context, key string, input interface{}, expire ...int) error
- func (self *CacheManager) Rpush(key string, val interface{}) error
- func (self *CacheManager) RpushWithContext(ctx context.Context, key string, val interface{}) error
- func (self *CacheManager) Size(pattern ...string) (int, error)
- func (self *CacheManager) SizeWithContext(ctx context.Context, pattern ...string) (int, error)
- func (self *CacheManager) Subscribe(key string, timeout int, call func(msg string) (bool, error)) error
- func (self *CacheManager) SubscribeAsync(key string, timeout int, call func(msg string) (bool, error), ...)
- func (self *CacheManager) SubscribeAsyncWithContext(ctx context.Context, key string, timeout int, ...)
- func (self *CacheManager) SubscribeWithContext(ctx context.Context, key string, timeout int, ...) error
- func (self *CacheManager) Values(pattern ...string) ([]interface{}, error)
- func (self *CacheManager) ValuesWithContext(ctx context.Context, pattern ...string) ([]interface{}, error)
- type LocalMapManager
- func (self *LocalMapManager) Del(key ...string) error
- func (self *LocalMapManager) Exists(key string) (bool, error)
- func (self *LocalMapManager) Flush() error
- func (self *LocalMapManager) Get(key string, input interface{}) (interface{}, bool, error)
- func (self *LocalMapManager) GetBool(key string) (bool, error)
- func (self *LocalMapManager) GetBytes(key string) ([]byte, error)
- func (self *LocalMapManager) GetFloat64(key string) (float64, error)
- func (self *LocalMapManager) GetInt64(key string) (int64, error)
- func (self *LocalMapManager) GetString(key string) (string, error)
- func (self *LocalMapManager) Keys(pattern ...string) ([]string, error)
- func (self *LocalMapManager) Mode() string
- func (self *LocalMapManager) NewCache(a, b int) Cache
- func (self *LocalMapManager) NewCacheWithEvict(a, b int, f func(interface{})) Cache
- func (self *LocalMapManager) Put(key string, input interface{}, expire ...int) error
- func (self *LocalMapManager) Size(pattern ...string) (int, error)
- func (self *LocalMapManager) Values(pattern ...string) ([]interface{}, error)
- type Lock
- func (lock *Lock) AcquireTime() time.Time
- func (lock *Lock) ExpireSeconds() int
- func (lock *Lock) HeldDuration() time.Duration
- func (lock *Lock) IsValid() bool
- func (lock *Lock) LastRefresh() time.Time
- func (lock *Lock) RefreshCount() int32
- func (lock *Lock) RefreshFailures() int32
- func (lock *Lock) Resource() string
- func (lock *Lock) TimeSinceLastRefresh() time.Duration
- func (lock *Lock) Token() string
- func (lock *Lock) Unlock() error
- type LockConfig
- type PutObj
- type RedisConfig
- type RedisManager
- func (self *RedisManager) BatchGet(keys []string) (map[string]interface{}, error)
- func (self *RedisManager) BatchGetString(keys []string) (map[string]string, error)
- func (self *RedisManager) BatchGetStringWithContext(ctx context.Context, keys []string) (map[string]string, error)
- func (self *RedisManager) BatchGetToTargets(keys []string, targets []interface{}) error
- func (self *RedisManager) BatchGetToTargetsContext(ctx context.Context, keys []string, targets []interface{}) error
- func (self *RedisManager) BatchGetWithContext(ctx context.Context, keys []string) (map[string]interface{}, error)
- func (self *RedisManager) BatchGetWithDeserializer(keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
- func (self *RedisManager) BatchGetWithDeserializerContext(ctx context.Context, keys []string, ...) (map[string]interface{}, error)
- func (self *RedisManager) Brpop(key string, expire int64, result interface{}) error
- func (self *RedisManager) BrpopBool(key string, expire int64) (bool, error)
- func (self *RedisManager) BrpopBoolWithContext(ctx context.Context, key string, expire int64) (bool, error)
- func (self *RedisManager) BrpopFloat64(key string, expire int64) (float64, error)
- func (self *RedisManager) BrpopFloat64WithContext(ctx context.Context, key string, expire int64) (float64, error)
- func (self *RedisManager) BrpopInt64(key string, expire int64) (int64, error)
- func (self *RedisManager) BrpopInt64WithContext(ctx context.Context, key string, expire int64) (int64, error)
- func (self *RedisManager) BrpopString(key string, expire int64) (string, error)
- func (self *RedisManager) BrpopStringWithContext(ctx context.Context, key string, expire int64) (string, error)
- func (self *RedisManager) BrpopWithContext(ctx context.Context, key string, expire int64, result interface{}) error
- func (self *RedisManager) Del(key ...string) error
- func (self *RedisManager) DelWithContext(ctx context.Context, key ...string) error
- func (self *RedisManager) Exists(key string) (bool, error)
- func (self *RedisManager) ExistsWithContext(ctx context.Context, key string) (bool, error)
- func (self *RedisManager) Flush() error
- func (self *RedisManager) FlushWithContext(ctx context.Context) error
- func (self *RedisManager) Get(key string, input interface{}) (interface{}, bool, error)
- func (self *RedisManager) GetBool(key string) (bool, error)
- func (self *RedisManager) GetBoolWithContext(ctx context.Context, key string) (bool, error)
- func (self *RedisManager) GetBytes(key string) ([]byte, error)
- func (self *RedisManager) GetBytesWithContext(ctx context.Context, key string) ([]byte, error)
- func (self *RedisManager) GetFloat64(key string) (float64, error)
- func (self *RedisManager) GetFloat64WithContext(ctx context.Context, key string) (float64, error)
- func (self *RedisManager) GetInt64(key string) (int64, error)
- func (self *RedisManager) GetInt64WithContext(ctx context.Context, key string) (int64, error)
- func (self *RedisManager) GetPoolStats() map[string]interface{}
- func (self *RedisManager) GetString(key string) (string, error)
- func (self *RedisManager) GetStringWithContext(ctx context.Context, key string) (string, error)
- func (self *RedisManager) GetWithContext(ctx context.Context, key string, input interface{}) (interface{}, bool, error)
- func (self *RedisManager) InitConfig(input ...RedisConfig) (*RedisManager, error)
- func (self *RedisManager) Keys(pattern ...string) ([]string, error)
- func (self *RedisManager) KeysWithContext(ctx context.Context, pattern ...string) ([]string, error)
- func (self *RedisManager) LogPoolStats()
- func (self *RedisManager) LuaScript(cmd string, key []string, val ...interface{}) (interface{}, error)
- func (self *RedisManager) LuaScriptWithContext(ctx context.Context, cmd string, key []string, val ...interface{}) (interface{}, error)
- func (self *RedisManager) Mode() string
- func (self *RedisManager) Publish(key string, val interface{}, try ...int) (bool, error)
- func (self *RedisManager) PublishWithContext(ctx context.Context, key string, val interface{}, try ...int) (bool, error)
- func (self *RedisManager) Put(key string, input interface{}, expire ...int) error
- func (self *RedisManager) PutBatch(objs ...*PutObj) error
- func (self *RedisManager) PutBatchWithContext(ctx context.Context, objs ...*PutObj) error
- func (self *RedisManager) PutWithContext(ctx context.Context, key string, input interface{}, expire ...int) error
- func (self *RedisManager) Rpush(key string, val interface{}) error
- func (self *RedisManager) RpushWithContext(ctx context.Context, key string, val interface{}) error
- func (self *RedisManager) Shutdown() error
- func (self *RedisManager) Size(pattern ...string) (int, error)
- func (self *RedisManager) SizeWithContext(ctx context.Context, pattern ...string) (int, error)
- func (self *RedisManager) Subscribe(key string, expSecond int, call func(msg string) (bool, error)) error
- func (self *RedisManager) SubscribeAsync(key string, expSecond int, call func(msg string) (bool, error), ...)
- func (self *RedisManager) SubscribeAsyncWithContext(ctx context.Context, key string, expSecond int, ...)
- func (self *RedisManager) SubscribeWithContext(ctx context.Context, key string, expSecond int, ...) error
- func (self *RedisManager) TryLockWithTimeout(resource string, expSecond int, call func(lock *Lock) error, ...) error
- func (self *RedisManager) Values(pattern ...string) ([]interface{}, error)deprecated
- func (self *RedisManager) ValuesWithContext(ctx context.Context, pattern ...string) ([]interface{}, error)deprecated
Constants ¶
const ( LOCAL = "local" REDIS = "redis" )
const ( // 连接池默认配置 DefaultMaxIdle = 50 // 默认最小空闲连接数 DefaultMaxActive = 200 // 默认最大连接数 DefaultMaxActiveLimit = 1000 // 默认最大连接数上限 // 超时配置 DefaultIdleTimeout = 1800 // 默认空闲连接超时时间(秒),30分钟,防止频繁重建连接 DefaultConnTimeout = 10 // 默认连接建立超时时间(秒) DefaultReadTimeout = 10 // 默认读取操作超时时间(秒) DefaultWriteTimeout = 10 // 默认写入操作超时时间(秒) DefaultPoolTimeout = 10 // 默认获取连接池连接超时时间(秒) // 高可用配置 DefaultMaxRetries = 3 // 默认最大重试次数 DefaultMinRetryBackoff = 8 // 默认最小重试间隔(毫秒) DefaultMaxRetryBackoff = 512 // 默认最大重试间隔(毫秒) // 性能监控配置 DefaultSlowCommandThreshold = 100 // 默认慢命令阈值(毫秒) // SCAN操作配置 DefaultScanCount = 100 // 默认SCAN命令每次迭代返回的键数量 // 批量操作配置 DefaultBatchChunkSize = 1000 // 默认批量操作每次管道操作的最大键数量 // 安全限制配置 DefaultMaxKeysForValues = 10000 // Values方法最大允许的键数量阈值,防止内存溢出 )
Redis配置默认值常量
Variables ¶
This section is empty.
Functions ¶
func ShutdownAllRedisManagers ¶ added in v1.1.0
func ShutdownAllRedisManagers()
ShutdownAllRedisManagers 关闭所有Redis管理器并清理资源 在程序退出时调用此函数,执行完整的资源清理 清理内容: - 立即清空全局映射,阻止新的连接请求(并发安全) - 关闭所有Redis客户端连接池(go-redis v9 会等待正在进行的命令完成) 注意事项: - HTTP服务器优雅关闭流程中已集成此调用 - 建议在main函数中添加 defer cache.ShutdownAllRedisManagers() 作为兜底保护 - 防止程序异常退出时Redis资源泄漏 - 并发安全:先清空映射再关闭,避免竞态条件 - go-redis v9 的关闭是优雅的,会等待正在进行的操作完成
使用示例:
func main() {
defer cache.ShutdownAllRedisManagers() // 🛡️ 兜底保护
// 业务逻辑...
}
func TryLocker ¶
func TryLocker(lockObj string, expSecond int, callObj func(lock *Lock) error, config ...*LockConfig) error
TryLocker 便捷函数:使用默认Redis管理器获取锁并执行回调 lockObj: 锁资源名称 expSecond: 锁过期时间(秒,>=3) callObj: 临界区回调函数,接收Lock实例用于状态检查 config: 可选的锁配置,默认使用DefaultLockConfig()
func ValidateLockConfig ¶ added in v1.1.0
func ValidateLockConfig(config *LockConfig) error
ValidateLockConfig 验证锁配置参数的合理性
Types ¶
type Cache ¶
type Cache interface {
// Mode 获取缓存实例的模式
// 返回:redis或local值
Mode() string
// Get 根据键获取缓存数据,支持自动反序列化
// key: 缓存键
// input: 目标对象类型,用于反序列化(可为nil)
// 返回: 缓存值、是否存在标志、错误信息
Get(key string, input interface{}) (interface{}, bool, error)
// GetWithContext 根据键获取缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// input: 目标对象类型,用于反序列化(可为nil)
// 返回: 缓存值、是否存在标志、错误信息
GetWithContext(ctx context.Context, key string, input interface{}) (interface{}, bool, error)
// GetInt64 获取64位整数缓存数据
// key: 缓存键
// 返回: 解析后的整数值或错误
GetInt64(key string) (int64, error)
// GetInt64WithContext 获取64位整数缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// 返回: 解析后的整数值或错误
GetInt64WithContext(ctx context.Context, key string) (int64, error)
// GetFloat64 获取64位浮点数缓存数据
// key: 缓存键
// 返回: 解析后的浮点数值或错误
GetFloat64(key string) (float64, error)
// GetFloat64WithContext 获取64位浮点数缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// 返回: 解析后的浮点数值或错误
GetFloat64WithContext(ctx context.Context, key string) (float64, error)
// GetString 获取字符串缓存数据
// key: 缓存键
// 返回: 字符串值或错误
GetString(key string) (string, error)
// GetStringWithContext 获取字符串缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// 返回: 字符串值或错误
GetStringWithContext(ctx context.Context, key string) (string, error)
// GetBytes 获取字节数组缓存数据
// key: 缓存键
// 返回: 字节数组或错误
GetBytes(key string) ([]byte, error)
// GetBytesWithContext 获取字节数组缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// 返回: 字节数组或错误
GetBytesWithContext(ctx context.Context, key string) ([]byte, error)
// GetBool 获取布尔值缓存数据
// key: 缓存键
// 返回: 布尔值或错误
GetBool(key string) (bool, error)
// GetBoolWithContext 获取布尔值缓存数据,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// 返回: 布尔值或错误
GetBoolWithContext(ctx context.Context, key string) (bool, error)
// Put 保存数据到缓存,可设置过期时间
// key: 缓存键
// input: 要缓存的数据
// expire: 过期时间(秒),可选,不设置则永久保存
// 返回: 操作错误
Put(key string, input interface{}, expire ...int) error
// PutWithContext 保存数据到缓存,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 缓存键
// input: 要缓存的数据
// expire: 过期时间(秒),可选,不设置则永久保存
// 返回: 操作错误
PutWithContext(ctx context.Context, key string, input interface{}, expire ...int) error
// PutBatch 批量保存数据到缓存
// objs: 批量保存对象列表,每个对象包含键、值和过期时间
// 返回: 操作错误
PutBatch(objs ...*PutObj) error
// PutBatchWithContext 批量保存数据到缓存,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// objs: 批量保存对象列表,每个对象包含键、值和过期时间
// 返回: 操作错误
PutBatchWithContext(ctx context.Context, objs ...*PutObj) error
// Del 删除一个或多个缓存键
// input: 要删除的缓存键列表
// 返回: 操作错误
Del(input ...string) error
// DelWithContext 删除一个或多个缓存键,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// input: 要删除的缓存键列表
// 返回: 操作错误
DelWithContext(ctx context.Context, input ...string) error
// Size 根据模式匹配统计键的数量
// pattern: 匹配模式,支持通配符"*"
// 返回: 匹配的键数量或错误
Size(pattern ...string) (int, error)
// SizeWithContext 根据模式匹配统计键的数量,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// pattern: 匹配模式,支持通配符"*"
// 返回: 匹配的键数量或错误
SizeWithContext(ctx context.Context, pattern ...string) (int, error)
// Keys 根据模式匹配获取键列表
// pattern: 匹配模式,支持通配符"*"
// 返回: 匹配的键列表或错误
Keys(pattern ...string) ([]string, error)
// KeysWithContext 根据模式匹配获取键列表,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// pattern: 匹配模式,支持通配符"*"
// 返回: 匹配的键列表或错误
KeysWithContext(ctx context.Context, pattern ...string) ([]string, error)
// Values 根据模式匹配获取所有键的值(性能警告:生产环境慎用)
// pattern: 匹配模式,支持通配符"*"
// 返回: 所有匹配键的值列表或错误
Values(pattern ...string) ([]interface{}, error)
// ValuesWithContext 根据模式匹配获取所有键的值,支持上下文控制(性能警告:生产环境慎用)
// ctx: 上下文,用于超时和取消控制
// pattern: 匹配模式,支持通配符"*"
// 返回: 所有匹配键的值列表或错误
ValuesWithContext(ctx context.Context, pattern ...string) ([]interface{}, error)
// BatchGet 批量获取多个缓存键的值
// keys: 要获取的缓存键列表
// 返回: 键值对映射或错误
BatchGet(keys []string) (map[string]interface{}, error)
// BatchGetWithContext 批量获取多个缓存键的值,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// keys: 要获取的缓存键列表
// 返回: 键值对映射或错误
BatchGetWithContext(ctx context.Context, keys []string) (map[string]interface{}, error)
// BatchGetWithDeserializer 批量获取并使用自定义反序列化函数处理
// keys: 要获取的缓存键列表
// deserializer: 自定义反序列化函数,输入键名和字节数组,返回反序列化结果和错误
// 返回: 键值对映射或错误
BatchGetWithDeserializer(keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
// BatchGetWithDeserializerContext 批量获取并使用自定义反序列化函数处理,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// keys: 要获取的缓存键列表
// deserializer: 自定义反序列化函数,输入键名和字节数组,返回反序列化结果和错误
// 返回: 键值对映射或错误
BatchGetWithDeserializerContext(ctx context.Context, keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
// BatchGetToTargets 批量获取并直接反序列化到预分配的目标对象列表(零反射版本)
// keys: 要获取的缓存键列表
// targets: 预分配的目标对象列表,与keys一一对应,必须都是非nil指针
// 返回: 操作错误
BatchGetToTargets(keys []string, targets []interface{}) error
// BatchGetToTargetsContext 批量获取并直接反序列化到预分配的目标对象列表,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// keys: 要获取的缓存键列表
// targets: 预分配的目标对象列表,与keys一一对应,必须都是非nil指针
// 返回: 操作错误
BatchGetToTargetsContext(ctx context.Context, keys []string, targets []interface{}) error
// Exists 检查缓存键是否存在
// key: 要检查的缓存键
// 返回: 存在标志和错误信息
Exists(key string) (bool, error)
// ExistsWithContext 检查缓存键是否存在,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 要检查的缓存键
// 返回: 存在标志和错误信息
ExistsWithContext(ctx context.Context, key string) (bool, error)
// Brpop 从列表右侧弹出元素,支持阻塞等待
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// result: 结果存储对象,用于反序列化
// 返回: 操作错误
Brpop(key string, expire int64, result interface{}) error
// BrpopWithContext 从列表右侧弹出元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// result: 结果存储对象,用于反序列化
// 返回: 操作错误
BrpopWithContext(ctx context.Context, key string, expire int64, result interface{}) error
// BrpopString 从列表右侧弹出字符串元素
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的字符串值或错误
BrpopString(key string, expire int64) (string, error)
// BrpopStringWithContext 从列表右侧弹出字符串元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的字符串值或错误
BrpopStringWithContext(ctx context.Context, key string, expire int64) (string, error)
// BrpopInt64 从列表右侧弹出64位整数元素
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的整数值或错误
BrpopInt64(key string, expire int64) (int64, error)
// BrpopInt64WithContext 从列表右侧弹出64位整数元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的整数值或错误
BrpopInt64WithContext(ctx context.Context, key string, expire int64) (int64, error)
// BrpopFloat64 从列表右侧弹出64位浮点数元素
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的浮点数值或错误
BrpopFloat64(key string, expire int64) (float64, error)
// BrpopFloat64WithContext 从列表右侧弹出64位浮点数元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的浮点数值或错误
BrpopFloat64WithContext(ctx context.Context, key string, expire int64) (float64, error)
// BrpopBool 从列表右侧弹出布尔值元素
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的布尔值或错误
BrpopBool(key string, expire int64) (bool, error)
// BrpopBoolWithContext 从列表右侧弹出布尔值元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// expire: 阻塞等待超时时间(秒)
// 返回: 弹出的布尔值或错误
BrpopBoolWithContext(ctx context.Context, key string, expire int64) (bool, error)
// Rpush 向列表右侧推入元素
// key: 列表键
// val: 要推入的值
// 返回: 操作错误
Rpush(key string, val interface{}) error
// RpushWithContext 向列表右侧推入元素,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 列表键
// val: 要推入的值
// 返回: 操作错误
RpushWithContext(ctx context.Context, key string, val interface{}) error
// Publish 发布消息到指定频道
// key: 频道名称
// val: 要发布的数据
// try: 重试次数,可选,默认3次
// 返回: 发布成功标志和错误信息
Publish(key string, val interface{}, try ...int) (bool, error)
// PublishWithContext 发布消息到指定频道,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// key: 频道名称
// val: 要发布的数据
// try: 重试次数,可选,默认3次
// 返回: 发布成功标志和错误信息
PublishWithContext(ctx context.Context, key string, val interface{}, try ...int) (bool, error)
// Subscribe 订阅指定频道,持续接收消息(阻塞方法)
// key: 频道名称
// timeout: 单个消息接收超时时间(秒),0表示无超时
// call: 消息处理回调函数,返回true停止订阅,false继续
// 返回: 操作错误或订阅被停止
Subscribe(key string, timeout int, call func(msg string) (bool, error)) error
// SubscribeWithContext 订阅指定频道,持续接收消息,支持上下文控制(阻塞方法)
// ctx: 上下文,用于超时和取消控制
// key: 频道名称
// timeout: 单个消息接收超时时间(秒),0表示无超时
// call: 消息处理回调函数,返回true停止订阅,false继续
// 返回: 操作错误或订阅被停止
SubscribeWithContext(ctx context.Context, key string, timeout int, call func(msg string) (bool, error)) error
// SubscribeAsync 异步订阅指定频道(非阻塞API)
// key: 频道名称
// timeout: 单个消息接收超时时间(秒),0表示无超时
// call: 消息处理回调函数,返回true停止订阅,false继续
// errorHandler: 订阅错误处理函数,可为nil
SubscribeAsync(key string, timeout int, call func(msg string) (bool, error), errorHandler func(error))
// SubscribeAsyncWithContext 异步订阅指定频道,支持上下文控制(非阻塞API)
// ctx: 上下文,用于超时和取消控制
// key: 频道名称
// timeout: 单个消息接收超时时间(秒),0表示无超时
// call: 消息处理回调函数,返回true停止订阅,false继续
// errorHandler: 订阅错误处理函数,可为nil
SubscribeAsyncWithContext(ctx context.Context, key string, timeout int, call func(msg string) (bool, error), errorHandler func(error))
// LuaScript 执行Lua脚本
// script: Lua脚本内容
// key: 脚本涉及的键列表
// val: 脚本参数列表
// 返回: 脚本执行结果或错误
LuaScript(script string, key []string, val ...interface{}) (interface{}, error)
// LuaScriptWithContext 执行Lua脚本,支持上下文控制
// ctx: 上下文,用于超时和取消控制
// script: Lua脚本内容
// key: 脚本涉及的键列表
// val: 脚本参数列表
// 返回: 脚本执行结果或错误
LuaScriptWithContext(ctx context.Context, script string, key []string, val ...interface{}) (interface{}, error)
// Flush 清空所有缓存数据(危险操作)
// 返回: 操作错误
Flush() error
// FlushWithContext 清空所有缓存数据,支持上下文控制(危险操作)
// ctx: 上下文,用于超时和取消控制
// 返回: 操作错误
FlushWithContext(ctx context.Context) error
}
缓存定义接口
func NewLocalCacheWithEvict ¶ added in v1.1.0
NewLocalCacheWithEvict 创建带淘汰回调的go-cache缓存实例 注意:go-cache不支持淘汰回调,此方法保留API兼容性
type CacheManager ¶
type CacheManager struct{}
缓存管理器
func (*CacheManager) BatchGet ¶ added in v1.1.0
func (self *CacheManager) BatchGet(keys []string) (map[string]interface{}, error)
func (*CacheManager) BatchGetToTargets ¶ added in v1.1.0
func (self *CacheManager) BatchGetToTargets(keys []string, targets []interface{}) error
func (*CacheManager) BatchGetToTargetsContext ¶ added in v1.1.0
func (self *CacheManager) BatchGetToTargetsContext(ctx context.Context, keys []string, targets []interface{}) error
func (*CacheManager) BatchGetWithContext ¶ added in v1.1.0
func (*CacheManager) BatchGetWithDeserializer ¶ added in v1.1.0
func (*CacheManager) BatchGetWithDeserializerContext ¶ added in v1.1.0
func (*CacheManager) Brpop ¶
func (self *CacheManager) Brpop(key string, expire int64, result interface{}) error
func (*CacheManager) BrpopBool ¶
func (self *CacheManager) BrpopBool(key string, expire int64) (bool, error)
func (*CacheManager) BrpopBoolWithContext ¶ added in v1.1.0
func (*CacheManager) BrpopFloat64 ¶
func (self *CacheManager) BrpopFloat64(key string, expire int64) (float64, error)
func (*CacheManager) BrpopFloat64WithContext ¶ added in v1.1.0
func (*CacheManager) BrpopInt64 ¶
func (self *CacheManager) BrpopInt64(key string, expire int64) (int64, error)
func (*CacheManager) BrpopInt64WithContext ¶ added in v1.1.0
func (*CacheManager) BrpopString ¶
func (self *CacheManager) BrpopString(key string, expire int64) (string, error)
func (*CacheManager) BrpopStringWithContext ¶ added in v1.1.0
func (*CacheManager) BrpopWithContext ¶ added in v1.1.0
func (*CacheManager) Del ¶
func (self *CacheManager) Del(key ...string) error
func (*CacheManager) DelWithContext ¶ added in v1.1.0
func (self *CacheManager) DelWithContext(ctx context.Context, key ...string) error
func (*CacheManager) Exists ¶ added in v1.0.92
func (self *CacheManager) Exists(key string) (bool, error)
func (*CacheManager) ExistsWithContext ¶ added in v1.1.0
func (*CacheManager) Flush ¶
func (self *CacheManager) Flush() error
func (*CacheManager) FlushWithContext ¶ added in v1.1.0
func (self *CacheManager) FlushWithContext(ctx context.Context) error
func (*CacheManager) Get ¶
func (self *CacheManager) Get(key string, input interface{}) (interface{}, bool, error)
func (*CacheManager) GetBoolWithContext ¶ added in v1.1.0
func (*CacheManager) GetBytes ¶ added in v1.0.154
func (self *CacheManager) GetBytes(key string) ([]byte, error)
func (*CacheManager) GetBytesWithContext ¶ added in v1.1.0
func (*CacheManager) GetFloat64 ¶
func (self *CacheManager) GetFloat64(key string) (float64, error)
func (*CacheManager) GetFloat64WithContext ¶ added in v1.1.0
func (*CacheManager) GetInt64WithContext ¶ added in v1.1.0
func (*CacheManager) GetStringWithContext ¶ added in v1.1.0
func (*CacheManager) GetWithContext ¶ added in v1.1.0
func (*CacheManager) KeysWithContext ¶ added in v1.1.0
func (*CacheManager) LuaScript ¶
func (self *CacheManager) LuaScript(script string, key []string, val ...interface{}) (interface{}, error)
func (*CacheManager) LuaScriptWithContext ¶ added in v1.1.0
func (*CacheManager) Mode ¶ added in v1.1.0
func (self *CacheManager) Mode() string
func (*CacheManager) Publish ¶
func (self *CacheManager) Publish(key string, val interface{}, try ...int) (bool, error)
func (*CacheManager) PublishWithContext ¶ added in v1.1.0
func (*CacheManager) Put ¶
func (self *CacheManager) Put(key string, input interface{}, expire ...int) error
func (*CacheManager) PutBatch ¶
func (self *CacheManager) PutBatch(objs ...*PutObj) error
func (*CacheManager) PutBatchWithContext ¶ added in v1.1.0
func (self *CacheManager) PutBatchWithContext(ctx context.Context, objs ...*PutObj) error
func (*CacheManager) PutWithContext ¶ added in v1.1.0
func (*CacheManager) Rpush ¶
func (self *CacheManager) Rpush(key string, val interface{}) error
func (*CacheManager) RpushWithContext ¶ added in v1.1.0
func (self *CacheManager) RpushWithContext(ctx context.Context, key string, val interface{}) error
func (*CacheManager) SizeWithContext ¶ added in v1.1.0
func (*CacheManager) Subscribe ¶
func (self *CacheManager) Subscribe(key string, timeout int, call func(msg string) (bool, error)) error
exp second
func (*CacheManager) SubscribeAsync ¶ added in v1.1.0
func (*CacheManager) SubscribeAsyncWithContext ¶ added in v1.1.0
func (*CacheManager) SubscribeWithContext ¶ added in v1.1.0
func (*CacheManager) Values ¶
func (self *CacheManager) Values(pattern ...string) ([]interface{}, error)
func (*CacheManager) ValuesWithContext ¶ added in v1.1.0
func (self *CacheManager) ValuesWithContext(ctx context.Context, pattern ...string) ([]interface{}, error)
type LocalMapManager ¶
type LocalMapManager struct {
CacheManager
// contains filtered or unexported fields
}
LocalMapManager 使用go-cache的本地缓存管理器
func (*LocalMapManager) Del ¶
func (self *LocalMapManager) Del(key ...string) error
func (*LocalMapManager) Exists ¶ added in v1.0.92
func (self *LocalMapManager) Exists(key string) (bool, error)
func (*LocalMapManager) Flush ¶
func (self *LocalMapManager) Flush() error
func (*LocalMapManager) Get ¶
func (self *LocalMapManager) Get(key string, input interface{}) (interface{}, bool, error)
func (*LocalMapManager) GetBytes ¶ added in v1.0.154
func (self *LocalMapManager) GetBytes(key string) ([]byte, error)
func (*LocalMapManager) GetFloat64 ¶
func (self *LocalMapManager) GetFloat64(key string) (float64, error)
func (*LocalMapManager) GetString ¶
func (self *LocalMapManager) GetString(key string) (string, error)
func (*LocalMapManager) Keys ¶ added in v1.1.0
func (self *LocalMapManager) Keys(pattern ...string) ([]string, error)
func (*LocalMapManager) Mode ¶ added in v1.1.0
func (self *LocalMapManager) Mode() string
func (*LocalMapManager) NewCache ¶
func (self *LocalMapManager) NewCache(a, b int) Cache
NewCache 创建go-cache缓存配置
func (*LocalMapManager) NewCacheWithEvict ¶ added in v1.1.0
func (self *LocalMapManager) NewCacheWithEvict(a, b int, f func(interface{})) Cache
NewCacheWithEvict 创建带淘汰回调的go-cache缓存 注意:go-cache不支持淘汰回调,此方法保留API兼容性
func (*LocalMapManager) Put ¶
func (self *LocalMapManager) Put(key string, input interface{}, expire ...int) error
func (*LocalMapManager) Values ¶ added in v1.0.152
func (self *LocalMapManager) Values(pattern ...string) ([]interface{}, error)
type Lock ¶
type Lock struct {
// contains filtered or unexported fields
}
Lock 表示一个已获取的分布式锁,包含自动续期能力
func (*Lock) AcquireTime ¶ added in v1.1.0
AcquireTime 获取锁的获取时间
func (*Lock) ExpireSeconds ¶ added in v1.1.0
ExpireSeconds 获取锁的过期时间(秒)
func (*Lock) HeldDuration ¶ added in v1.1.0
HeldDuration 获取锁的持有时长
func (*Lock) IsValid ¶ added in v1.1.0
IsValid 检查锁是否仍然有效 返回值: true表示锁仍然有效且可用,false表示锁已失效或已释放(续期失败或已释放)
func (*Lock) LastRefresh ¶ added in v1.1.0
LastRefresh 获取最后续期时间
func (*Lock) RefreshCount ¶ added in v1.1.0
RefreshCount 获取续期成功次数
func (*Lock) RefreshFailures ¶ added in v1.1.0
RefreshFailures 获取续期失败次数
func (*Lock) TimeSinceLastRefresh ¶ added in v1.1.0
TimeSinceLastRefresh 获取距离最后续期的时长
type LockConfig ¶ added in v1.1.0
type LockConfig struct {
// 基础时间配置(8字节字段)
MinExpireSeconds int // 最小过期时间(秒),默认3秒,防止过期时间过短
// 比例配置(8字节字段)
RefreshIntervalRatio float64 // 续期间隔比例,默认1/3,即过期时间的1/3时进行续期
AcquireTimeoutRatio float64 // 获取锁超时比例,默认1/2,即最多等待过期时间的一半
// 重试次数配置(8字节字段)
MaxRefreshRetries int // 最大续期重试次数,默认2次,防止无限重试
MaxAcquireRetries int // 获取锁最大重试次数,默认3次,防止无限重试
// 时间间隔配置(8字节字段)
MinRetryBackoff time.Duration // 最小重试间隔,默认100毫秒,避免过于频繁重试
MaxRetryBackoff time.Duration // 最大重试间隔,默认2秒,避免等待过久
RefreshRetryBackoff time.Duration // 续期重试间隔,默认100毫秒,续期需要及时重试
}
LockConfig 分布式锁配置参数
func DefaultLockConfig ¶ added in v1.1.0
func DefaultLockConfig() *LockConfig
DefaultLockConfig 返回默认的锁配置
type RedisConfig ¶
type RedisConfig struct {
DsName string // 数据源名称,用于区分多个Redis实例
Host string // Redis服务器主机地址
Port int // Redis服务器端口号
Password string // Redis认证密码(可选)
MaxIdle int // 连接池最小空闲连接数,默认50,映射到go-redis的MinIdleConns,必须小于等于MaxActive
MaxActive int // 连接池最大连接数,默认200,映射到go-redis的PoolSize,建议不超过MaxActiveLimit配置值
MaxActiveLimit int // 连接池最大连接数上限,默认1000,用于防止配置过大导致Redis服务器压力过大
IdleTimeout int // 空闲连接超时时间(秒),默认1800(30分钟),建议不小于60秒以避免频繁创建连接
Network string // 网络协议,默认tcp
ConnTimeout int // 连接建立超时时间(秒),默认10
ReadTimeout int // 读取操作超时时间(秒),默认10
WriteTimeout int // 写入操作超时时间(秒),默认10
PoolTimeout int // 获取连接池连接的超时时间(秒),默认10,建议不超过30秒以避免无限阻塞
// 高可用和重连配置
MaxRetries int // 最大重试次数,默认3,生产环境建议5-10
MinRetryBackoff int // 最小重试间隔(毫秒),默认8ms
MaxRetryBackoff int // 最大重试间隔(毫秒),默认512ms
// 性能监控配置
EnableCommandMonitoring bool // 是否启用命令耗时监控,默认false,启用后会记录Redis命令的执行时间
SlowCommandThreshold int // 慢命令阈值(毫秒),默认100ms,超过此值记录警告日志,便于排查性能瓶颈
EnableDetailedLogs bool // 是否启用详细命令日志,默认false,仅记录慢命令日志以减少性能影响。启用后会记录所有命令的详细信息
// SCAN操作配置
ScanCount int // SCAN命令每次迭代返回的键数量,默认100,建议根据键数量调整(100-10000之间)。过大可能导致单次扫描耗时过长,过小可能增加迭代次数
// 批量操作配置
BatchChunkSize int // PutBatch每次管道操作的最大键数量,默认1000,防止单次操作过大导致阻塞
EnableBatchDetailedLogs bool // 是否启用批量操作详细日志,默认false,仅在调试模式下启用分片详情日志
// 危险操作配置
AllowFlush bool // 是否允许Flush操作,默认false,生产环境应禁用以防止误操作
}
RedisConfig Redis连接配置结构体 定义了Redis服务器连接所需的所有参数
连接池配置重要说明: - MaxActive(PoolSize): 连接池最大连接数,建议不超过MaxActiveLimit配置值,过大会增加Redis服务器压力 - MaxActiveLimit: 连接池最大连接数上限,默认1000,可根据Redis服务器maxclients配置调整 - MaxIdle(MinIdleConns): 最小空闲连接数,必须小于等于MaxActive,否则会被MaxActive限制 - IdleTimeout: 空闲连接超时时间,建议不小于60秒,避免频繁创建连接;默认1800秒(30分钟) - PoolTimeout: 获取连接池连接的超时时间,建议不超过30秒,避免无限阻塞;默认10秒 - 配置关系要求: MaxIdle <= MaxActive <= MaxActiveLimit, IdleTimeout >= 60, PoolTimeout <= 30 - Redis服务器承载能力: 单实例通常支持1000-10000并发连接,需根据实际maxclients配置调整MaxActiveLimit
危险操作配置说明: - AllowFlush: 是否允许Flush操作,生产环境必须设为false以防止误操作 - 测试/开发环境可设为true,但使用时要非常谨慎
配置建议: - 低并发 (< 1000 QPS): MaxIdle=10, MaxActive=50, IdleTimeout=300, PoolTimeout=10, AllowFlush=false, EnableDetailedLogs=false, EnableBatchDetailedLogs=false - 中并发 (1000-5000 QPS): MaxIdle=30, MaxActive=200, IdleTimeout=1800, PoolTimeout=10, AllowFlush=false, EnableDetailedLogs=false, EnableBatchDetailedLogs=false - 高并发 (> 5000 QPS): MaxIdle=50, MaxActive=500, IdleTimeout=3600, PoolTimeout=15, AllowFlush=false, EnableDetailedLogs=false, EnableBatchDetailedLogs=false (MaxActive不超过1000) - 超高并发: 考虑使用Redis集群或增加Redis实例, AllowFlush=false, EnableDetailedLogs=false, EnableBatchDetailedLogs=false - 测试环境: 可设置AllowFlush=true用于清理测试数据, EnableDetailedLogs=true用于调试, EnableBatchDetailedLogs=true用于调试批量操作 - 调试环境: 可设置EnableDetailedLogs=true记录所有命令详情,EnableBatchDetailedLogs=true记录批量操作详情,但会影响性能
高可用配置建议: - MaxRetries: 生产环境建议5-10,开发环境可设为3 - MinRetryBackoff: 建议8ms,MaxRetryBackoff: 建议512ms - 重连间隔会按指数退避策略增加,确保网络抖动时的稳定性
type RedisManager ¶
type RedisManager struct {
CacheManager // 嵌入基础缓存管理器
// 字符串字段(16字节对齐)
DsName string // 数据源名称标识
// 指针字段(8字节对齐)
RedisClient *redis.Client // go-redis v9 客户端
// contains filtered or unexported fields
}
RedisManager Redis缓存管理器 实现了Cache接口,基于 go-redis v9 库提供高性能Redis缓存操作
func NewRedis ¶
func NewRedis(ds ...string) (*RedisManager, error)
NewRedis 创建新的Redis管理器实例 ds: 数据源名称,可选,默认为DIC.MASTER 返回: Redis管理器实例或错误
func (*RedisManager) BatchGet ¶ added in v1.1.0
func (self *RedisManager) BatchGet(keys []string) (map[string]interface{}, error)
BatchGet 批量获取多个缓存键的值(分片优化版本,避免大批量操作阻塞) keys: 要获取的缓存键列表 返回: 键值对映射和错误信息
注意: - 大批量键自动分片为多个小批次(默认1000个/批),防止单次操作阻塞Redis - 使用MGet命令批量获取,减少网络往返 - 分片处理保证内存使用可控,不会一次性加载过多数据
func (*RedisManager) BatchGetString ¶ added in v1.1.0
func (self *RedisManager) BatchGetString(keys []string) (map[string]string, error)
BatchGetString 批量获取字符串类型缓存数据(分片优化版本,避免大批量操作阻塞) keys: 要获取的缓存键列表 返回: 键值对映射和错误信息
注意: - 大批量键自动分片为多个小批次(默认1000个/批),防止单次操作阻塞Redis - 直接使用Redis MGet命令批量获取原始字符串值,避免额外的反序列化开销 - 对于不存在的键,返回nil(不会包含在结果中) - 字符串类型直接返回原始格式,不进行JSON处理 - 分片处理保证内存使用可控,不会一次性加载过多数据
func (*RedisManager) BatchGetStringWithContext ¶ added in v1.1.0
func (self *RedisManager) BatchGetStringWithContext(ctx context.Context, keys []string) (map[string]string, error)
BatchGetStringWithContext 批量获取字符串类型缓存数据(分片优化版本,支持上下文) ctx: 上下文,用于超时和取消控制 keys: 要获取的缓存键列表 返回: 键值对映射和错误信息
注意: - 大批量键自动分片为多个小批次(默认1000个/批),防止单次操作阻塞Redis - 直接使用Redis MGet命令批量获取原始字符串值,避免额外的反序列化开销 - 对于不存在的键,返回nil(不会包含在结果中) - 字符串类型直接返回原始格式,不进行JSON处理 - 分片处理保证内存使用可控,不会一次性加载过多数据 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) BatchGetToTargets ¶ added in v1.1.0
func (self *RedisManager) BatchGetToTargets(keys []string, targets []interface{}) error
BatchGetToTargets 批量获取并直接反序列化到预分配的目标对象列表(零反射版本) keys: 要获取的缓存键列表 targets: 预分配的目标对象列表,与keys一一对应 返回: 操作错误
注意: - 完全避免反射使用,提供最佳性能 - keys和targets长度必须相等,否则返回错误 - 目标对象必须是指针类型,用于接收反序列化结果 - 适用于预知结果类型和数量的批量操作场景
使用示例:
var users []*User
var configs []*Config
keys := []string{"user:1", "user:2", "config:app"}
targets := []interface{}{&users[0], &users[1], &configs[0]}
err := cache.BatchGetToTargets(keys, targets)
func (*RedisManager) BatchGetToTargetsContext ¶ added in v1.1.0
func (self *RedisManager) BatchGetToTargetsContext(ctx context.Context, keys []string, targets []interface{}) error
BatchGetToTargetsContext 批量获取并直接反序列化到预分配的目标对象列表(零反射版本,支持上下文) ctx: 上下文,用于超时和取消控制 keys: 要获取的缓存键列表 targets: 预分配的目标对象列表,与keys一一对应 返回: 操作错误
注意: - 完全避免反射使用,提供最佳性能 - 大批量键自动分片处理,防止阻塞Redis - keys和targets长度必须相等,否则返回错误 - 目标对象必须是非nil指针类型(如 &User{}),nil指针会导致panic - 支持基础类型和复杂对象的反序列化,与Get方法行为一致 - 不存在的键对应的目标对象保持不变
性能优势: - 零反射开销,性能最佳 - 内存预分配,避免运行时对象创建 - 类型安全,编译时保证类型正确性 - 适合高频批量操作场景
func (*RedisManager) BatchGetWithContext ¶ added in v1.1.0
func (self *RedisManager) BatchGetWithContext(ctx context.Context, keys []string) (map[string]interface{}, error)
BatchGetWithContext 批量获取多个缓存键的值(分片优化版本,支持上下文) ctx: 上下文,用于超时和取消控制 keys: 要获取的缓存键列表 返回: 键值对映射和错误信息
注意: - 大批量键自动分片为多个小批次(默认1000个/批),防止单次操作阻塞Redis - 使用MGet命令批量获取,减少网络往返 - 分片处理保证内存使用可控,不会一次性加载过多数据 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) BatchGetWithDeserializer ¶ added in v1.1.0
func (self *RedisManager) BatchGetWithDeserializer(keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
BatchGetWithDeserializer 批量获取并使用自定义反序列化函数处理(零反射版本) keys: 要获取的缓存键列表 deserializer: 自定义反序列化函数,输入键名和字节数组,返回反序列化结果和错误 返回: 键值对映射和错误信息
注意: - 完全避免反射使用,提供最佳性能 - 适用于性能要求极高的场景 - 反序列化逻辑完全由用户控制,可以根据不同key进行差异化处理
使用示例:
result, err := cache.BatchGetWithDeserializer(keys, func(key string, data []byte) (interface{}, error) {
// 可以根据key进行不同的反序列化逻辑
if strings.HasPrefix(key, "user:") {
var user User
return user, json.Unmarshal(data, &user)
} else if strings.HasPrefix(key, "config:") {
var config Config
return config, json.Unmarshal(data, &config)
}
return data, nil // 返回原始数据
})
func (*RedisManager) BatchGetWithDeserializerContext ¶ added in v1.1.0
func (self *RedisManager) BatchGetWithDeserializerContext(ctx context.Context, keys []string, deserializer func(string, []byte) (interface{}, error)) (map[string]interface{}, error)
BatchGetWithDeserializerContext 批量获取并使用自定义反序列化函数处理(零反射版本,支持上下文) ctx: 上下文,用于超时和取消控制 keys: 要获取的缓存键列表 deserializer: 自定义反序列化函数,输入键名和字节数组,返回反序列化结果和错误 返回: 键值对映射和错误信息
注意: - 完全避免反射使用,提供最佳性能 - 大批量键自动分片处理,防止阻塞Redis - 适用于性能要求极高的场景 - 反序列化逻辑完全由用户控制,可以根据不同key进行差异化处理 - 失败时返回原始字节数组,保证数据不丢失
性能优势: - 零反射开销,性能最佳 - 用户控制的反序列化逻辑,可以优化内存分配 - 支持基于key的条件反序列化,灵活性高 - 适合高频批量操作场景
func (*RedisManager) Brpop ¶
func (self *RedisManager) Brpop(key string, expire int64, result interface{}) error
Brpop 从列表右侧弹出元素并反序列化到指定对象 key: 列表键 expire: 阻塞等待超时时间(秒) result: 反序列化目标对象,支持基础类型和复杂类型 返回: 操作错误
注意: - 对于复杂类型,自动JSON反序列化 - 对于基础类型,直接赋值(数据以原始格式存储) - 复用Get方法的deserializeValue逻辑,确保行为一致
func (*RedisManager) BrpopBool ¶
func (self *RedisManager) BrpopBool(key string, expire int64) (bool, error)
BrpopBool 从列表右侧弹出布尔值元素 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的布尔值或错误
func (*RedisManager) BrpopBoolWithContext ¶ added in v1.1.0
func (self *RedisManager) BrpopBoolWithContext(ctx context.Context, key string, expire int64) (bool, error)
BrpopBoolWithContext 从列表右侧弹出布尔值元素(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的布尔值或错误
func (*RedisManager) BrpopFloat64 ¶
func (self *RedisManager) BrpopFloat64(key string, expire int64) (float64, error)
BrpopFloat64 从列表右侧弹出64位浮点数元素 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的浮点数值或错误
func (*RedisManager) BrpopFloat64WithContext ¶ added in v1.1.0
func (self *RedisManager) BrpopFloat64WithContext(ctx context.Context, key string, expire int64) (float64, error)
BrpopFloat64WithContext 从列表右侧弹出64位浮点数元素(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的浮点数值或错误
func (*RedisManager) BrpopInt64 ¶
func (self *RedisManager) BrpopInt64(key string, expire int64) (int64, error)
BrpopInt64 从列表右侧弹出64位整数元素 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的整数值或错误
func (*RedisManager) BrpopInt64WithContext ¶ added in v1.1.0
func (self *RedisManager) BrpopInt64WithContext(ctx context.Context, key string, expire int64) (int64, error)
BrpopInt64WithContext 从列表右侧弹出64位整数元素(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的整数值或错误
func (*RedisManager) BrpopString ¶
func (self *RedisManager) BrpopString(key string, expire int64) (string, error)
BrpopString 从列表右侧弹出字符串元素,支持阻塞等待 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的字符串值或错误
func (*RedisManager) BrpopStringWithContext ¶ added in v1.1.0
func (self *RedisManager) BrpopStringWithContext(ctx context.Context, key string, expire int64) (string, error)
BrpopStringWithContext 从列表右侧弹出字符串元素,支持阻塞等待(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 expire: 阻塞等待超时时间(秒) 返回: 弹出的字符串值或错误
func (*RedisManager) BrpopWithContext ¶ added in v1.1.0
func (self *RedisManager) BrpopWithContext(ctx context.Context, key string, expire int64, result interface{}) error
BrpopWithContext 从列表右侧弹出元素并反序列化到指定对象(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 expire: 阻塞等待超时时间(秒) result: 反序列化目标对象,支持基础类型和复杂类型 返回: 操作错误
注意: - 对于复杂类型,自动JSON反序列化 - 对于基础类型,直接赋值(数据以原始格式存储) - 复用Get方法的deserializeValue逻辑,确保行为一致 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) Del ¶
func (self *RedisManager) Del(key ...string) error
Del 删除一个或多个缓存键,使用Redis事务保证原子性 key: 要删除的缓存键列表 返回: 操作错误
func (*RedisManager) DelWithContext ¶ added in v1.1.0
func (self *RedisManager) DelWithContext(ctx context.Context, key ...string) error
DelWithContext 删除一个或多个缓存键,使用Redis事务保证原子性(支持上下文) ctx: 上下文,用于超时和取消控制 key: 要删除的缓存键列表 返回: 操作错误
func (*RedisManager) Exists ¶ added in v1.0.92
func (self *RedisManager) Exists(key string) (bool, error)
Exists 检查缓存键是否存在 key: 缓存键 返回: 是否存在、操作错误
func (*RedisManager) ExistsWithContext ¶ added in v1.1.0
ExistsWithContext 检查缓存键是否存在(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 是否存在、操作错误
func (*RedisManager) Flush ¶
func (self *RedisManager) Flush() error
Flush 清空当前数据库的所有缓存数据 返回: 操作错误
注意: - 使用Redis FLUSHDB命令清空当前数据库的所有键 - 此操作不可逆,生产环境请谨慎使用 - 主要用于测试环境或开发环境的清理工作 - 执行前会记录警告日志,建议在生产环境禁用此功能
安全警告: - 生产环境应通过配置AllowFlush=false禁用此方法 - 执行此操作前请确保有数据备份 - 建议使用更精确的键删除操作代替全量清空
func (*RedisManager) FlushWithContext ¶ added in v1.1.0
func (self *RedisManager) FlushWithContext(ctx context.Context) error
FlushWithContext 清空当前数据库的所有缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 返回: 操作错误
注意: - 使用Redis FLUSHDB命令清空当前数据库的所有键 - 此操作不可逆,生产环境请谨慎使用 - 主要用于测试环境或开发环境的清理工作 - 执行前会记录警告日志,建议在生产环境禁用此功能
安全警告: - 生产环境应通过配置AllowFlush=false禁用此方法 - 执行此操作前请确保有数据备份 - 建议使用更精确的键删除操作代替全量清空 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) Get ¶
func (self *RedisManager) Get(key string, input interface{}) (interface{}, bool, error)
Get 获取缓存数据并可选择反序列化 key: 缓存键 input: 反序列化目标对象,为nil时返回原始字节数组 返回: 缓存数据、是否存在、错误
注意: - 基础类型在Redis中以原始格式存储,直接赋值 - 复杂类型在Redis中以JSON格式存储,自动反序列化 - input为nil时返回原始字节数组
func (*RedisManager) GetBool ¶
func (self *RedisManager) GetBool(key string) (bool, error)
GetBool 获取布尔值缓存数据 key: 缓存键 返回: 布尔值或错误
func (*RedisManager) GetBoolWithContext ¶ added in v1.1.0
GetBoolWithContext 获取布尔值缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 布尔值或错误
func (*RedisManager) GetBytes ¶ added in v1.0.154
func (self *RedisManager) GetBytes(key string) ([]byte, error)
GetBytes 获取字节数组缓存数据 key: 缓存键 返回: 字节数组或错误
func (*RedisManager) GetBytesWithContext ¶ added in v1.1.0
GetBytesWithContext 获取字节数组缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 字节数组或错误
func (*RedisManager) GetFloat64 ¶
func (self *RedisManager) GetFloat64(key string) (float64, error)
GetFloat64 获取64位浮点数缓存数据 key: 缓存键 返回: 解析后的浮点数值或错误
func (*RedisManager) GetFloat64WithContext ¶ added in v1.1.0
GetFloat64WithContext 获取64位浮点数缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 解析后的浮点数值或错误
func (*RedisManager) GetInt64 ¶
func (self *RedisManager) GetInt64(key string) (int64, error)
GetInt64 获取64位整数缓存数据 key: 缓存键 返回: 解析后的整数值或错误
func (*RedisManager) GetInt64WithContext ¶ added in v1.1.0
GetInt64WithContext 获取64位整数缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 解析后的整数值或错误
func (*RedisManager) GetPoolStats ¶ added in v1.1.0
func (self *RedisManager) GetPoolStats() map[string]interface{}
GetPoolStats 获取连接池统计信息 返回连接池的活跃连接数、空闲连接数等统计信息
func (*RedisManager) GetString ¶
func (self *RedisManager) GetString(key string) (string, error)
GetString 获取字符串缓存数据 key: 缓存键 返回: 字符串值或错误
func (*RedisManager) GetStringWithContext ¶ added in v1.1.0
GetStringWithContext 获取字符串缓存数据(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 返回: 字符串值或错误
func (*RedisManager) GetWithContext ¶ added in v1.1.0
func (self *RedisManager) GetWithContext(ctx context.Context, key string, input interface{}) (interface{}, bool, error)
GetWithContext 获取缓存数据并可选择反序列化(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 input: 反序列化目标对象,为nil时返回原始字节数组 返回: 缓存数据、是否存在、错误
注意: - 基础类型在Redis中以原始格式存储,直接赋值 - 复杂类型在Redis中以JSON格式存储,自动反序列化 - input为nil时返回原始字节数组 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) InitConfig ¶
func (self *RedisManager) InitConfig(input ...RedisConfig) (*RedisManager, error)
InitConfig 初始化Redis连接配置 支持多个数据源配置,并发安全,支持重复调用检测 input: 一个或多个Redis配置 返回: 初始化后的Redis管理器实例或错误
func (*RedisManager) Keys ¶
func (self *RedisManager) Keys(pattern ...string) ([]string, error)
Keys 根据模式匹配获取键列表(使用SCAN命令,生产环境安全) pattern: 匹配模式,支持通配符"*" 返回: 匹配的键列表或错误
注意: - 使用SCAN命令替代KEYS命令,避免阻塞Redis服务 - SCAN是渐进式扫描,不会阻塞其他操作 - 每次迭代返回的键数量可通过RedisConfig.ScanCount配置 - 适合在生产环境中使用,特别适用于大量键的场景
func (*RedisManager) KeysWithContext ¶ added in v1.1.0
KeysWithContext 根据模式匹配获取键列表(使用SCAN命令,支持上下文) ctx: 上下文,用于超时和取消控制 pattern: 匹配模式,支持通配符"*" 返回: 匹配的键列表或错误
注意: - 使用SCAN命令替代KEYS命令,避免阻塞Redis服务 - SCAN是渐进式扫描,不会阻塞其他操作 - 每次迭代返回的键数量可通过RedisConfig.ScanCount配置 - 适合在生产环境中使用,特别适用于大量键的场景 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) LogPoolStats ¶ added in v1.1.0
func (self *RedisManager) LogPoolStats()
LogPoolStats 记录连接池统计信息到日志
func (*RedisManager) LuaScript ¶
func (self *RedisManager) LuaScript(cmd string, key []string, val ...interface{}) (interface{}, error)
LuaScript 执行Lua脚本,支持键和参数传递 cmd: Lua脚本内容 key: 脚本涉及的键列表 val: 脚本参数列表,直接使用原始类型不强制转换 返回: 脚本执行结果或错误
func (*RedisManager) LuaScriptWithContext ¶ added in v1.1.0
func (self *RedisManager) LuaScriptWithContext(ctx context.Context, cmd string, key []string, val ...interface{}) (interface{}, error)
LuaScriptWithContext 执行Lua脚本,支持键和参数传递(支持上下文) ctx: 上下文,用于超时和取消控制 cmd: Lua脚本内容 key: 脚本涉及的键列表 val: 脚本参数列表,直接使用原始类型不强制转换 返回: 脚本执行结果或错误
func (*RedisManager) Mode ¶ added in v1.1.0
func (self *RedisManager) Mode() string
func (*RedisManager) Publish ¶
func (self *RedisManager) Publish(key string, val interface{}, try ...int) (bool, error)
Publish 发布消息到指定频道,支持网络错误重试 key: 频道名称 val: 要发布的值,会转换为字符串 try: 可选的重试次数,默认3次,仅对网络错误重试 返回: 是否有订阅者接收、操作错误
注意: - 仅对网络错误进行重试,无订阅者不属于错误,无需重试 - PUBLISH命令返回值表示接收消息的客户端数量,0表示无订阅者 - 网络错误使用指数退避重试策略
func (*RedisManager) PublishWithContext ¶ added in v1.1.0
func (self *RedisManager) PublishWithContext(ctx context.Context, key string, val interface{}, try ...int) (bool, error)
PublishWithContext 发布消息到指定频道,支持网络错误重试(支持上下文) ctx: 上下文,用于超时和取消控制 key: 频道名称 val: 要发布的值,会转换为字符串 try: 可选的重试次数,默认3次,仅对网络错误重试 返回: 是否有订阅者接收、操作错误
注意: - 仅对网络错误进行重试,无订阅者不属于错误,无需重试 - PUBLISH命令返回值表示接收消息的客户端数量,0表示无订阅者 - 网络错误使用指数退避重试策略 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) Put ¶
func (self *RedisManager) Put(key string, input interface{}, expire ...int) error
Put 存储缓存数据,支持过期时间设置 key: 缓存键 input: 要缓存的数据,支持[]byte、string或其他类型 expire: 可选的过期时间(秒),不设置表示永久缓存 返回: 操作错误
注意: - 对于基础类型(string, []byte, int, int64, float64, bool),直接存储 - 对于复杂类型(结构体等),自动JSON序列化后存储 - 确保数据存储格式的一致性和可读性
func (*RedisManager) PutBatch ¶
func (self *RedisManager) PutBatch(objs ...*PutObj) error
PutBatch 批量存储缓存数据,使用分片管道提高性能 objs: 批量存储对象数组,每个对象包含键、值和过期时间 返回: 操作错误
注意: - 对每个值的处理逻辑与Put方法相同 - 大批量自动分片为多个小批次(默认1000个/批),防止单次操作阻塞 - 使用Redis管道批量发送命令,减少网络往返 - 不保证原子性,但性能更好,适合大多数批量操作场景 - 如需原子性保证,请使用Put方法逐个设置或使用Lua脚本
func (*RedisManager) PutBatchWithContext ¶ added in v1.1.0
func (self *RedisManager) PutBatchWithContext(ctx context.Context, objs ...*PutObj) error
PutBatchWithContext 批量存储缓存数据,使用分片管道提高性能(支持上下文) ctx: 上下文,用于超时和取消控制 objs: 批量存储对象数组,每个对象包含键、值和过期时间 返回: 操作错误
注意: - 对每个值的处理逻辑与Put方法相同 - 大批量自动分片为多个小批次(默认1000个/批),防止单次操作阻塞 - 使用Redis管道批量发送命令,减少网络往返 - 不保证原子性,但性能更好,适合大多数批量操作场景 - 如需原子性保证,请使用Put方法逐个设置或使用Lua脚本 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) PutWithContext ¶ added in v1.1.0
func (self *RedisManager) PutWithContext(ctx context.Context, key string, input interface{}, expire ...int) error
PutWithContext 存储缓存数据,支持过期时间设置(支持上下文) ctx: 上下文,用于超时和取消控制 key: 缓存键 input: 要缓存的数据,支持[]byte、string或其他类型 expire: 可选的过期时间(秒),不设置表示永久缓存 返回: 操作错误
注意: - 对于基础类型(string, []byte, int, int64, float64, bool),直接存储 - 对于复杂类型(结构体等),自动JSON序列化后存储 - 确保数据存储格式的一致性和可读性 - 支持通过context.Context进行超时和取消控制
func (*RedisManager) Rpush ¶
func (self *RedisManager) Rpush(key string, val interface{}) error
Rpush 向列表右侧推入元素 key: 列表键 val: 要推入的值,会转换为字符串存储 返回: 操作错误
func (*RedisManager) RpushWithContext ¶ added in v1.1.0
func (self *RedisManager) RpushWithContext(ctx context.Context, key string, val interface{}) error
RpushWithContext 向列表右侧推入元素(支持上下文) ctx: 上下文,用于超时和取消控制 key: 列表键 val: 要推入的值,会转换为字符串存储 返回: 操作错误
func (*RedisManager) Shutdown ¶ added in v1.1.0
func (self *RedisManager) Shutdown() error
Shutdown 关闭RedisManager,清理所有资源 关闭 go-redis 客户端(自带连接池管理和健康检查) 注意: go-redis v9 的 Close() 会等待所有正在进行的命令完成后再关闭连接池
func (*RedisManager) Size ¶
func (self *RedisManager) Size(pattern ...string) (int, error)
Size 根据模式获取匹配键的数量 pattern: 匹配模式 返回: 匹配键的数量或错误
func (*RedisManager) SizeWithContext ¶ added in v1.1.0
SizeWithContext 根据模式获取匹配键的数量(支持上下文) ctx: 上下文,用于超时和取消控制 pattern: 匹配模式 返回: 匹配键的数量或错误
func (*RedisManager) Subscribe ¶
func (self *RedisManager) Subscribe(key string, expSecond int, call func(msg string) (bool, error)) error
Subscribe 订阅指定频道,持续接收消息 key: 频道名称 expSecond: 单个消息接收超时时间(秒),0表示无超时,持续等待 call: 消息处理回调函数,返回true停止订阅,false继续 返回: 操作错误或订阅被停止
注意: - 不同于原始设计,现在expSecond控制单次消息接收超时,而非整个订阅生命周期 - 如果expSecond > 0,每次等待消息都有超时限制,超时后继续等待下一条消息 - 如果expSecond = 0,无超时限制,持续等待消息直到明确停止 - 只有当消息处理函数返回true或出错时才会停止订阅 - 当Redis连接断开时,会自动检测通道关闭并退出,避免死锁 Subscribe 订阅指定频道,持续接收消息 key: 频道名称 expSecond: 单个消息接收超时时间(秒),0表示无超时,持续等待 call: 消息处理回调函数,返回true停止订阅,false继续 返回: 操作错误或订阅被停止
重要警告: - 此方法是阻塞的,必须在goroutine中调用 - 详情请参考 SubscribeWithContext 方法的完整文档
func (*RedisManager) SubscribeAsync ¶ added in v1.1.0
func (self *RedisManager) SubscribeAsync(key string, expSecond int, call func(msg string) (bool, error), errorHandler func(error))
SubscribeAsync 异步订阅指定频道(非阻塞API) key: 频道名称 expSecond: 单个消息接收超时时间(秒),0表示无超时,持续等待 call: 消息处理回调函数,返回true停止订阅,false继续 errorHandler: 订阅错误处理函数,可为nil
安全特性: - 自动在goroutine中启动订阅,避免阻塞调用者 - 提供错误处理回调,便于错误监控 - 订阅失败时不会panic,只会调用errorHandler
使用示例:
cache.SubscribeAsync("channel", 30,
func(msg string) (bool, error) {
// 处理消息逻辑
return false, nil
},
func(err error) {
// 处理订阅错误
log.Printf("订阅失败: %v", err)
})
func (*RedisManager) SubscribeAsyncWithContext ¶ added in v1.1.0
func (self *RedisManager) SubscribeAsyncWithContext(ctx context.Context, key string, expSecond int, call func(msg string) (bool, error), errorHandler func(error))
SubscribeAsyncWithContext 异步订阅指定频道(支持上下文的非阻塞API) ctx: 上下文,用于超时和取消控制 key: 频道名称 expSecond: 单个消息接收超时时间(秒),0表示无超时,持续等待 call: 消息处理回调函数,返回true停止订阅,false继续 errorHandler: 订阅错误处理函数,可为nil
安全特性: - 自动在goroutine中启动订阅,避免阻塞调用者 - 支持上下文取消,可通过ctx控制订阅生命周期 - 提供错误处理回调,便于错误监控 - 订阅失败时不会panic,只会调用errorHandler
上下文控制: - ctx.Done() 触发时会优雅停止订阅 - 支持超时控制,通过context.WithTimeout创建ctx - 支持取消控制,通过context.WithCancel创建ctx
使用示例:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
cache.SubscribeAsyncWithContext(ctx, "channel", 30,
func(msg string) (bool, error) {
// 处理消息逻辑
return false, nil // 返回false继续订阅
},
func(err error) {
// 处理订阅错误
log.Printf("订阅失败: %v", err)
})
func (*RedisManager) SubscribeWithContext ¶ added in v1.1.0
func (self *RedisManager) SubscribeWithContext(ctx context.Context, key string, expSecond int, call func(msg string) (bool, error)) error
SubscribeWithContext 订阅指定频道,持续接收消息(支持上下文) ctx: 上下文,用于超时和取消控制 key: 频道名称 expSecond: 单个消息接收超时时间(秒),明确语义如下:
- expSecond > 0: 每次消息接收的超时时间,到期后继续等待下一条消息
- expSecond = 0: 无超时限制,持续等待直到上下文取消或连接断开
- 重要:这不是整个订阅的生命周期超时,而是单次消息接收的超时
call: 消息处理回调函数,返回true停止订阅,false继续 返回: 操作错误或订阅被停止
重要警告: - 此方法是阻塞的,会持续运行直到订阅被停止或出错 - 必须在单独的goroutine中调用,避免阻塞主线程 - 错误的调用方式会阻塞整个应用程序
正确使用示例:
// 示例1: 有超时的订阅(30秒内没收到消息则超时,但继续等待)
go func() {
err := cache.SubscribeWithContext(ctx, "channel", 30, func(msg string) (bool, error) {
// 处理消息,每30秒必须收到至少一条消息,否则会记录超时但继续等待
return false, nil // 返回false继续订阅
})
if err != nil {
log.Printf("订阅错误: %v", err)
}
}()
// 示例2: 无超时的订阅(持续等待直到手动停止)
go func() {
err := cache.SubscribeWithContext(ctx, "channel", 0, func(msg string) (bool, error) {
// 处理消息,无超时限制
return false, nil // 返回false继续订阅
})
if err != nil {
log.Printf("订阅错误: %v", err)
}
}()
错误使用示例(会阻塞主线程):
err := cache.SubscribeWithContext(ctx, "channel", 30, handler) // ❌ 阻塞主线程!
超时语义说明: - expSecond控制的是"单次消息接收"的超时,不是整个订阅的超时 - 当expSecond > 0时,每收到一条消息后,会重置超时计时器 - 如果长时间没有消息,超过expSecond秒后会记录超时日志,但订阅会继续 - 真正的订阅终止只能通过: 消息处理函数返回true、上下文取消、连接断开或发生错误
自动重连: - 当Redis连接断开时,会自动尝试重连(最多3次) - 重连成功后,订阅会无缝继续,无需手动干预 - 重连失败后,订阅会终止并返回错误
func (*RedisManager) TryLockWithTimeout ¶
func (self *RedisManager) TryLockWithTimeout(resource string, expSecond int, call func(lock *Lock) error, config ...*LockConfig) error
TryLockWithTimeout 尝试获取分布式锁,带超时控制,并执行回调函数 resource: 锁资源名称(如"order:10086") expSecond: 锁初始过期时间(秒,建议>=3) call: 临界区回调函数,接收Lock实例用于状态检查(获取锁后执行) config: 可选的锁配置,默认使用DefaultLockConfig()
func (*RedisManager) Values
deprecated
func (self *RedisManager) Values(pattern ...string) ([]interface{}, error)
Values 根据模式匹配获取键对应的所有值 pattern: 匹配模式,支持通配符"*" 返回: 值列表或错误
注意: - 性能敏感操作,大量键时可能影响性能和内存使用 - 内部通过Keys获取键列表,然后批量获取值 - 一次性加载所有数据到内存,可能导致内存溢出
🚨 强烈推荐使用分页处理替代方案:
// 推荐的分页处理方式 - 内存安全,性能可控
keys, err := cache.Keys("user:*")
if err != nil { return err }
const batchSize = 1000 // 每批处理1000个键
for i := 0; i < len(keys); i += batchSize {
end := i + batchSize
if end > len(keys) { end = len(keys) }
batchKeys := keys[i:end]
values, err := cache.BatchGet(batchKeys...)
if err != nil { return err }
// 处理这一批数据...
for key, value := range values {
// 处理单个键值对...
}
}
Deprecated: 此方法可能导致严重的内存和性能问题,强烈建议使用Keys+BatchGet分页组合替代
func (*RedisManager) ValuesWithContext
deprecated
added in
v1.1.0
func (self *RedisManager) ValuesWithContext(ctx context.Context, pattern ...string) ([]interface{}, error)
ValuesWithContext 根据模式匹配获取键对应的所有值(支持上下文) ctx: 上下文,用于超时和取消控制 pattern: 匹配模式,支持通配符"*" 返回: 值列表或错误
注意: - 性能敏感操作,大量键时可能影响性能和内存使用 - 内部通过Keys获取键列表,然后批量获取值 - 一次性加载所有数据到内存,可能导致内存溢出 - 安全限制: 最多只允许处理DefaultMaxKeysForValues个键,超过此限制将返回错误
🚨 强烈推荐使用分页处理替代方案:
// 推荐的分页处理方式 - 内存安全,性能可控
keys, err := cache.KeysWithContext(ctx, "user:*")
if err != nil { return err }
const batchSize = 1000 // 每批处理1000个键
for i := 0; i < len(keys); i += batchSize {
end := i + batchSize
if end > len(keys) { end = len(keys) }
batchKeys := keys[i:end]
values, err := cache.BatchGetWithContext(ctx, batchKeys...)
if err != nil { return err }
// 处理这一批数据...
for key, value := range values {
// 处理单个键值对...
}
}
Deprecated: 此方法可能导致严重的内存和性能问题,强烈建议使用Keys+BatchGet分页组合替代