Help us shape the future of Go! Take the 2026 Go Developer Survey

lock

package
v0.10.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package lock 提供同步任务的并发控制原语:

  • 跨实例互斥锁:oekit redisx/distlock(SetNX + Lua 原子解锁 + 自动续期), 本包只负责固定 key 前缀与客户端构造;
  • Semaphore:基于 redis ZSET 的分布式信号量,限制全局并发上限;
  • LocalLock:单实例(未配 redis)时的进程内互斥。

Index

Constants

View Source
const (

	// LockKeyPrefix 是跨实例互斥锁的 key 前缀。distlock 以 "<prefix>:<key>" 落 key,
	// 与迁移前自写实现的 "git-sync:lock:<key>" 布局一致:滚动升级期间新老实例
	// 看到的是同一把锁,不会出现两边各持一把而同时执行的窗口。
	LockKeyPrefix = "git-sync:lock"
)

Variables

This section is empty.

Functions

func NewLocker added in v0.10.0

NewLocker 构造跨实例互斥锁,key 前缀固定为 LockKeyPrefix;续期等策略由调用方按场景追加。

func NewRedisClient added in v0.10.0

func NewRedisClient(addr, password string, db int, opts ...Option) *redis.Client

NewRedisClient 按地址与连接池参数构造 go-redis 客户端,供 NewLocker / NewSemaphore 共用。

Types

type LocalLock

type LocalLock struct {
	// contains filtered or unexported fields
}

func NewLocalLock

func NewLocalLock() *LocalLock

func (*LocalLock) Lock

func (l *LocalLock) Lock(ctx context.Context, key string) error

func (*LocalLock) TryLock

func (l *LocalLock) TryLock(ctx context.Context, key string) (bool, error)

func (*LocalLock) TryLockWithTTL

func (l *LocalLock) TryLockWithTTL(ctx context.Context, key string, ttl time.Duration) (bool, error)

func (*LocalLock) Unlock

func (l *LocalLock) Unlock(ctx context.Context, key string) error

type Option

type Option func(*redis.Options)

Option functional option for NewRedisClient.

func WithPoolOptions

func WithPoolOptions(pool RedisPoolOptions) Option

WithPoolOptions 设置连接池参数。

type RedisPoolOptions

type RedisPoolOptions struct {
	PoolSize        int // 连接池大小,默认 10*GOMAXPROCS
	MinIdleConns    int // 最小空闲连接数,默认 0(冷启动无预热)
	DialTimeoutSec  int // 建连超时秒数,默认使用 OS TCP 超时
	ReadTimeoutSec  int // 读超时秒数
	WriteTimeoutSec int // 写超时秒数
}

RedisPoolOptions 连接池可选配置,零值使用 go-redis 默认。

type Semaphore

type Semaphore struct {
	// contains filtered or unexported fields
}

func NewSemaphore

func NewSemaphore(client *redis.Client, key string, max int, slotTTL time.Duration) *Semaphore

NewSemaphore 创建一个基于 redis ZSET 的分布式信号量。 slotTTL 为单个槽的存活时长:持有者需周期性 Renew,进程崩溃后槽在 slotTTL 后自动释放。

func (*Semaphore) Acquire

func (s *Semaphore) Acquire(ctx context.Context, identifier string) (bool, error)

func (*Semaphore) Cleanup

func (s *Semaphore) Cleanup(ctx context.Context, olderThan time.Duration) error

func (*Semaphore) Release

func (s *Semaphore) Release(ctx context.Context, identifier string) error

func (*Semaphore) Renew

func (s *Semaphore) Renew(ctx context.Context, identifier string) error

Renew 续期持有的槽(把 score 推到 now+slotTTL),仅当成员已存在才续期。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL