Documentation
¶
Index ¶
Constants ¶
View Source
const (
Name = "redis_component"
)
Variables ¶
View Source
var ( // ErrLockNotObtained 在规定时间/重试次数内未能获取到锁时返回 ErrLockNotObtained = errors.New("redis lock: lock not obtained") // ErrLockNotHeld 释放或续期时,发现锁已不属于当前持有者(已过期或被他人持有) ErrLockNotHeld = errors.New("redis lock: lock not held") // ErrClientNil redis client 为空(通常是 redis 组件未初始化) ErrClientNil = errors.New("redis lock: redis client is nil") )
Functions ¶
Types ¶
type Component ¶
func NewComponent ¶
func NewComponent() *Component
func (*Component) OnAfterInit ¶
func (s *Component) OnAfterInit()
type Lock ¶ added in v1.0.20
type Lock struct {
// contains filtered or unexported fields
}
Lock 基于 Redis 实现的分布式锁。
通过 SET key token NX PX 获取锁,使用唯一 token 标识持有者, 释放/续期均通过 Lua 脚本校验 token,保证只有持有者才能操作,避免误删。 可选开启看门狗(watchdog)在持锁期间自动续期,防止业务未结束锁就过期。
func NewLockWithInstance ¶ added in v1.0.20
NewLockWithInstance 使用全局 redis 组件实例创建分布式锁, 并自动拼接 redis 组件配置的 PrefixKey 前缀。
func (*Lock) Lock ¶ added in v1.0.20
Lock 阻塞式获取锁,按 retryInterval 重试,直到获取成功或 ctx 结束。 若 ctx 超时/取消仍未获取到,返回 ctx.Err() 或 ErrLockNotObtained。
func (*Lock) Renew ¶ added in v1.0.20
Renew 手动续期,将锁的过期时间重设为 ttl。 仅当前 token 持有锁时有效,否则返回 ErrLockNotHeld。
type Option ¶ added in v1.0.20
type Option func(*Lock)
Option 配置分布式锁的可选项
func WithAutoRenew ¶ added in v1.0.20
func WithAutoRenew() Option
WithAutoRenew 开启看门狗,在成功获取锁后自动定时续期, 直到调用 Unlock 或获取锁时使用的 ctx 被取消。
func WithRetryInterval ¶ added in v1.0.20
WithRetryInterval 设置阻塞获取锁(Lock)时的重试间隔,默认 100ms。
Click to show internal directories.
Click to hide internal directories.