Documentation
¶
Overview ¶
Package cache 提供基于 Redis 的缓存接入:连接管理、基础命令封装、分布式锁与延迟队列。
上下文管理: 本包所有封装方法均不接收 context 参数, 单次命令的上下文超时时间在 连接配置 Redis.ContextTimeout 中统一设定(未设置时默认 3s), 由封装内部为每次命令创建带超时的 context, 业务方无需在每次调用时传递超时参数。
app.Boot 场景经 Wire 一行接入(建连 + Ping 探活 + 关停释放):
app.MustRun(&app.Boot[Conf]{
Wire: func(c *Conf) []app.Component {
return []app.Component{cache.NewBoot(&c.Redis)}
},
})
Redis 连接为全局单例: Connect 注入包级全局 Client(), Wire 中放置多个 cache.Boot 会互相覆盖。
独立使用:
r := &cache.Redis{
Host: "127.0.0.1",
Port: 6379,
Password: "123456",
// 超时/连接池/锁配置可不设, 未设置(<=0)时自动使用默认值
}
if err := r.Connect(); err != nil { // 建连 + Ping 探活, 成功后注入全局
panic(err)
}
defer cache.Close()
// 基础命令, 任意位置直接调用
_ = cache.Set("name", "note", time.Minute)
name, _ := cache.Get("name")
// 分布式锁(锁被占用时按配置自旋等待)
lock, err := cache.Lock("lock:order:1", time.Minute)
if err != nil {
return // 获取失败
}
defer lock.Unlock()
// 延迟队列: sorted set 承载, 到期投递, 失败自动重试
q := cache.NewDelayQueue("orders:delay", func(payload string) error {
return process(payload)
})
_ = q.Start() // Init 钩子中启动消费协程
defer q.Stop() // Close 钩子中停止并等待在途消息
_ = q.Push("order:1", 30*time.Second) // 30s 后可消费
本包未封装的高级命令(Scan/BLPop/Pipeline/订阅等)通过 Client() 获取原生客户端执行。
Index ¶
- Variables
- func Client() redis.UniversalClient
- func Close() error
- func Decr(key string) (int64, error)
- func DecrBy(key string, decrement int64) (int64, error)
- func Del(keys ...string) (int64, error)
- func Exists(keys ...string) (int64, error)
- func Expire(key string, expiration time.Duration) (bool, error)
- func Get(key string) (string, error)
- func HDel(key string, fields ...string) (int64, error)
- func HGet(key string, field string) (string, error)
- func HGetAll(key string) (map[string]string, error)
- func HMSet(key string, m map[string]any) error
- func HSet(key string, field string, value any) error
- func Incr(key string) (int64, error)
- func IncrBy(key string, increment int64) (int64, error)
- func LLen(key string) (int64, error)
- func LPop(key string) (string, error)
- func LPush(key string, values ...any) (int64, error)
- func LRange(key string, start, stop int64) ([]string, error)
- func MGet(keys ...string) ([]any, error)
- func MSet(pairs ...any) error
- func Persist(key string) (bool, error)
- func RPop(key string) (string, error)
- func RPush(key string, values ...any) (int64, error)
- func SAdd(key string, members ...any) (int64, error)
- func SCard(key string) (int64, error)
- func SIsMember(key string, member any) (bool, error)
- func SMembers(key string) ([]string, error)
- func SRem(key string, members ...any) (int64, error)
- func Set(key string, value any, expiration time.Duration) error
- func SetClient(c redis.UniversalClient)
- func SetNX(key string, value any, expiration time.Duration) (bool, error)
- func TTL(key string) (time.Duration, error)
- func ZAdd(key string, members ...ZMember) (int64, error)
- func ZCard(key string) (int64, error)
- func ZRange(key string, start, stop int64) ([]string, error)
- func ZRem(key string, members ...any) (int64, error)
- func ZScore(key string, member any) (float64, error)
- type Boot
- type DelayQueue
- type DistributedLock
- type Redis
- type RedisPool
- type ZMember
Constants ¶
This section is empty.
Variables ¶
var ( // ErrLockNotAcquired 未获取到锁: 锁被其他持有者占用, 或自旋等待超时 ErrLockNotAcquired = errors.New("lock not acquired") // ErrLockNotHeld 释放/续期失败: 锁已过期或不再由当前持有者持有 ErrLockNotHeld = errors.New("lock not held") )
分布式锁相关错误
var Nil = redis.Nil
Nil key 不存在时命令返回的错误(同 redis.Nil), 调用方可用 errors.Is 判断
Functions ¶
func SetClient ¶
func SetClient(c redis.UniversalClient)
SetClient 设置全局 redis 客户端, 用于手动注入(如 cluster/sentinel 场景)
Types ¶
type Boot ¶ added in v1.0.4
type Boot struct {
// Redis 连接配置
Redis *Redis
}
Boot 组件适配器: 一行接入 app.Boot 的 Wire 装配钩子(结构化匹配 app.Component 约定, 无需 import app)。Redis 连接为全局单例: Connect 注入包级全局 Client(), Wire 中放置多个 cache.Boot 会互相覆盖。
type DelayQueue ¶ added in v1.0.4
type DelayQueue struct {
// PollInterval 消费轮询间隔(<=0 时默认 1s), 决定投递精度下限
PollInterval time.Duration
// BatchSize 单轮最多取出的到期消息数(<=0 时默认 10)
BatchSize int
// MaxAttempts 最大尝试次数, 含首次消费(<=0 时默认 3)
MaxAttempts int
// RetryDelay 消费失败后的重试等待时长(<=0 时默认 1s)
RetryDelay time.Duration
// contains filtered or unexported fields
}
DelayQueue 基于 sorted set 的延迟队列: 以到期时间(毫秒时间戳)作 score, 消费协程轮询到期消息, 原子 ZREM 抢占成功后执行回调; 回调失败按 重试策略(Attempts/RetryDelay/MaxAttempts)重新入队, 超过最大尝试次数丢弃并记日志。
多实例部署时天然分摊消息(ZREM 原子抢占, 谁删到谁消费); 单队列为单协程顺序消费, 回调内不宜执行长阻塞任务。
func NewDelayQueue ¶ added in v1.0.4
func NewDelayQueue(key string, handler func(payload string) error) *DelayQueue
NewDelayQueue 创建延迟队列: key 为 redis 中的 sorted set 键名, handler 为消费回调(返回 nil 表示消费成功, 返回 error 触发重试)。 Start 之前可用字段调整轮询/重试策略。
func (*DelayQueue) Push ¶ added in v1.0.4
func (q *DelayQueue) Push(payload string, delay time.Duration) error
Push 投递一条消息: delay 之后可被消费(delay<=0 立即可消费)。 与队列是否已 Start 无关, 未连接 redis 时返回错误。
func (*DelayQueue) Start ¶ added in v1.0.4
func (q *DelayQueue) Start() error
Start 启动消费协程(非阻塞), 重复调用返回错误。 接入 app.Boot 时在 Init 钩子中调用。
func (*DelayQueue) Stop ¶ added in v1.0.4
func (q *DelayQueue) Stop()
Stop 停止消费并等待在途回调执行完成, 可重复调用。 接入 app.Boot 时在 Close 钩子中调用。
type DistributedLock ¶
type DistributedLock struct {
// contains filtered or unexported fields
}
DistributedLock 分布式锁, 由 TryLock/Lock 获取成功后返回
func Lock ¶
func Lock(key string, expiration time.Duration) (*DistributedLock, error)
Lock 获取分布式锁: 锁空闲时立即返回; 锁被占用时按配置的重试间隔 (Redis.LockRetryInterval, 默认 100ms)自旋重试, 超出配置的最大等待时间 (Redis.LockWaitTimeout, 默认 5s)仍未获取则返回 ErrLockNotAcquired; 未经 Connect 注入配置时(等待时间为 0)等价于 TryLock, 仅尝试一次
func TryLock ¶
func TryLock(key string, expiration time.Duration) (*DistributedLock, error)
TryLock 尝试获取分布式锁, 仅尝试一次: 锁空闲时获取成功, 锁被占用时立即返回 ErrLockNotAcquired。 expiration 为锁的过期时间, 必须大于 0(防止持有者异常退出后锁永不释放)
func (*DistributedLock) Extend ¶
func (l *DistributedLock) Extend(expiration time.Duration) (bool, error)
Extend 续期锁: 仅当锁仍由当前持有者持有时才将其过期时间重置为 expiration, 续期失败(锁已过期或被其他持有者持有)时返回 false
func (*DistributedLock) Unlock ¶
func (l *DistributedLock) Unlock() error
Unlock 释放锁: 仅当锁仍由当前持有者持有时才删除; 锁已过期或被其他持有者持有时返回 ErrLockNotHeld
type Redis ¶
type Redis struct {
RedisPool // 连接池配置
Host string `yaml:"host" toml:"host" json:"host" mapstructure:"host"` // redis 主机
Port int `yaml:"port" toml:"port" json:"port" mapstructure:"port"` // redis 端口
Username string `yaml:"username" toml:"username" json:"username" mapstructure:"username"` // 用户名(redis 6.0+ acl)
Password string `yaml:"password" toml:"password" json:"password" mapstructure:"password"` // 密码
DB int `yaml:"db" toml:"db" json:"db" mapstructure:"db"` // 数据库编号
// 超时配置, 封装内部创建命令 context 时使用
DialTimeout time.Duration `yaml:"dial_timeout" toml:"dial_timeout" json:"dial_timeout" mapstructure:"dial_timeout"` // 建立连接的超时时间(<=0 时默认 5s)
ReadTimeout time.Duration `yaml:"read_timeout" toml:"read_timeout" json:"read_timeout" mapstructure:"read_timeout"` // 读取(命令执行)的超时时间(<=0 时默认 3s)
WriteTimeout time.Duration `yaml:"write_timeout" toml:"write_timeout" json:"write_timeout" mapstructure:"write_timeout"` // 写入的超时时间(<=0 时默认 3s)
ContextTimeout time.Duration `yaml:"context_timeout" toml:"context_timeout" json:"context_timeout" mapstructure:"context_timeout"` // 单次命令的上下文超时时间(<=0 时默认 3s)
// 分布式锁配置
LockWaitTimeout time.Duration `yaml:"lock_wait_timeout" toml:"lock_wait_timeout" json:"lock_wait_timeout" mapstructure:"lock_wait_timeout"` // Lock 自旋获取锁的最大等待时间(<=0 时默认 5s, 仅尝试一次请使用 TryLock)
LockRetryInterval time.Duration `yaml:"lock_retry_interval" toml:"lock_retry_interval" json:"lock_retry_interval" mapstructure:"lock_retry_interval"` // Lock 自旋获取锁的重试间隔(<=0 时默认 100ms)
}
Redis redis 连接配置
type RedisPool ¶
type RedisPool struct {
PoolSize int `yaml:"pool_size" toml:"pool_size" json:"pool_size" mapstructure:"pool_size"` // 连接池最大连接数
MaxIdleConns int `yaml:"max_idle_conns" toml:"max_idle_conns" json:"max_idle_conns" mapstructure:"max_idle_conns"` // 连接池最大空闲连接数
MinIdleConns int `yaml:"min_idle_conns" toml:"min_idle_conns" json:"min_idle_conns" mapstructure:"min_idle_conns"` // 连接池最小空闲连接数(提前建立并保活)
ConnMaxIdleTime time.Duration `yaml:"conn_max_idle_time" toml:"conn_max_idle_time" json:"conn_max_idle_time" mapstructure:"conn_max_idle_time"` // 连接最大空闲时间
ConnMaxLifetime time.Duration `yaml:"conn_max_lifetime" toml:"conn_max_lifetime" json:"conn_max_lifetime" mapstructure:"conn_max_lifetime"` // 连接最大生命周期
MaxRetries int `yaml:"max_retries" toml:"max_retries" json:"max_retries" mapstructure:"max_retries"` // 命令执行失败的最大重试次数(-1 表示禁用重试)
}
RedisPool redis 连接池配置