Documentation
¶
Overview ¶
Package cache 提供基于 Redis 的缓存接入:连接管理、基础命令封装与分布式锁。
上下文管理: 本包所有封装方法均不接收 context 参数, 单次命令的上下文超时时间在 连接配置 Redis.ContextTimeout 中统一设定(未设置时默认 3s), 由封装内部为每次命令创建带超时的 context, 业务方无需在每次调用时传递超时参数。
使用示例:
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()
本包未封装的高级命令(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 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 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 连接池配置