Documentation
¶
Index ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrNotObtained = errors.New("distlock: lock not obtained")
ErrNotObtained 当锁已被其他节点持有、无法获取时返回。 调用方用 errors.Is(err, distlock.ErrNotObtained) 判断。
Functions ¶
This section is empty.
Types ¶
type EtcdLocker ¶
type EtcdLocker struct {
// contains filtered or unexported fields
}
EtcdLocker 基于 etcd mutex 的分布式锁实现。
func (*EtcdLocker) Close ¶
func (l *EtcdLocker) Close() error
type EtcdOptions ¶
type EtcdOptions struct {
// DialTimeout 是 etcd 连接超时;默认 5s。
DialTimeout time.Duration
// SessionTTL 是 session 续约租约秒数;默认 5s。
SessionTTL int
// SessionTimeout 是创建会话超时;默认 5s。
SessionTimeout time.Duration
}
EtcdOptions 配置 etcd 分布式锁行为。
type Lock ¶
type Lock interface {
// Key 返回锁的键名。
Key() string
// Release 立即释放锁。
// 若锁已过期或已被释放,返回底层错误。
Release(ctx context.Context) error
// Refresh 以原始 TTL 续期一次。
Refresh(ctx context.Context) error
// StartRefresh 启动后台续期协程,每隔配置的 RefreshInterval 调用一次 Refresh。
//
// - onError 在每次续期失败时调用(可为 nil);无论 onError 返回什么,失败后协程自动退出。
// - 返回的 stop 函数取消续期协程并阻塞等待其退出;可安全多次调用(幂等)。
//
// 典型用法:
//
// stop := lock.StartRefresh(ctx, func(err error) { log.Warn(err) })
// defer stop()
StartRefresh(ctx context.Context, onError func(err error)) (stop func())
}
Lock 代表一把已持有的分布式锁。
type Locker ¶
type Locker interface {
// Obtain 尝试获取 key 对应的锁。
// - 成功:返回 Lock,调用方必须在完成后调用 Release。
// - 锁已被持有:返回 ErrNotObtained(可用 errors.Is 判断)。
// - 其他错误:返回底层错误。
Obtain(ctx context.Context, key string) (Lock, error)
// Close 关闭后端资源;不再使用时调用。
Close() error
}
Locker 抽象分布式锁后端(Redis/Etcd 等),供上层业务统一依赖。
func NewEtcd ¶
func NewEtcd(endpoints []string, opts EtcdOptions) (Locker, error)
NewEtcd 创建基于 etcd concurrency.Session + Mutex 的锁实现。
func NewEtcdWithClient ¶
func NewEtcdWithClient(cli *clientv3.Client, opts EtcdOptions) Locker
NewEtcdWithClient 使用已有 etcd client 创建 locker(便于复用连接)。
type Options ¶
type Options struct {
// TTL 是锁的有效期;默认 30s。
TTL time.Duration
// MaxRetries 是争抢锁时的最大重试次数;默认 10 次。
MaxRetries int
// RetryDelay 是线性退避的步长;默认 100ms。
RetryDelay time.Duration
// RefreshInterval 是 StartRefresh 的续期间隔;默认 TTL/3。
RefreshInterval time.Duration
}
Options 配置锁的获取与续期行为。零值字段自动使用内置默认值。
type RedisLocker ¶
type RedisLocker struct {
// contains filtered or unexported fields
}
RedisLocker 是基于 redislock 的分布式锁实现。
Click to show internal directories.
Click to hide internal directories.