Documentation
¶
Index ¶
- func GetService(ctx context.Context) (datacontract.DistributedLock, error)
- func Lock(ctx context.Context, key string, ttl time.Duration) error
- func MustGetService(ctx context.Context) datacontract.DistributedLock
- func TryLock(ctx context.Context, key string, ttl time.Duration) (bool, error)
- func Unlock(ctx context.Context, key string) error
- func WithLock(ctx context.Context, key string, ttl time.Duration, fn func() error) error
- type DistributedLock
- type DistributedLockConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetService ¶ added in v0.1.4
func GetService(ctx context.Context) (datacontract.DistributedLock, error)
GetService 从容器中获取分布式锁服务实例。 通过 context 解析容器,再从容器中解析 DistributedLockKey 对应的服务。 如果容器未注册分布式锁服务,返回错误。
GetService retrieves the distributed lock service from the container resolved via ctx. Returns an error if the service is not registered.
func Lock ¶
Lock 使用分布式锁服务获取锁。 通过 context 解析容器获取分布式锁服务,然后调用其 Lock 方法。 key 为锁的标识,ttl 为锁的存活时间。
Lock acquires a lock using the distributed lock service resolved from ctx. key is the lock identifier, ttl is the time-to-live of the lock.
func MustGetService ¶ added in v0.1.4
func MustGetService(ctx context.Context) datacontract.DistributedLock
MustGetService 从容器中获取分布式锁服务实例,失败时 panic。 适用于确定已注册分布式锁服务的场景,简化错误处理。
MustGetService retrieves the distributed lock service from the container resolved via ctx. Panics if the service is not registered.
func TryLock ¶
TryLock 使用分布式锁服务尝试获取锁。 通过 context 解析容器获取分布式锁服务,然后调用其 TryLock 方法。 返回是否成功获取锁及可能的错误。
TryLock tries to acquire a lock using the distributed lock service resolved from ctx. Returns whether the lock was acquired and any error encountered.
func Unlock ¶
Unlock 使用分布式锁服务释放锁。 通过 context 解析容器获取分布式锁服务,然后调用其 Unlock 方法。
Unlock releases a lock using the distributed lock service resolved from ctx.
func WithLock ¶
WithLock 使用分布式锁包裹执行函数,执行完毕后自动释放锁。 通过 context 解析容器获取分布式锁服务,获取锁后执行 fn,执行完毕后释放锁。
示例:
err := dlock.WithLock(ctx, "order:42", 5*time.Second, func() error {
return processOrder(ctx, 42)
})
WithLock executes fn while holding a distributed lock resolved from ctx. The lock is released after fn completes.
Example:
err := dlock.WithLock(ctx, "order:42", 5*time.Second, func() error {
return processOrder(ctx, 42)
})
Types ¶
type DistributedLock ¶
type DistributedLock = datacontract.DistributedLock
DistributedLock 是分布式锁契约的顶层别名。 DistributedLock is the top-level alias of the distributed lock contract.
type DistributedLockConfig ¶
type DistributedLockConfig = datacontract.DistributedLockConfig
DistributedLockConfig 是分布式锁配置契约的顶层别名。 DistributedLockConfig is the top-level alias of the distributed lock config contract.