lock

package
v0.0.0-...-b69e565 Latest Latest
Warning

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

Go to latest
Published: Jul 9, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package lock implements a basic distributed lock that is held in N redis instances. Normally N should be 1, but the package supports multiple instances to support migrating from one instance to another.

The locking primitives exposed by this package should not be used for any application in which the lock is critical for correctness. The guarantees that can be made by a lock of this nature are only suitable for applications which lock for efficiency (e.g. in order to avoid doing expensive work, such as refilling a cache, multiple times).

When backed by multiple redis instances, locks will be acquired in the order given by the redis.Cmdable slice. To avoid deadlocks, ensure every Locker client uses the same ordering of redis clients.

Index

Constants

This section is empty.

Variables

View Source
var ErrLockNotAcquired = errors.New("locker: did not acquire lock")
View Source
var ErrLockNotHeld = errors.New("locker: lock was not held")

Functions

This section is empty.

Types

type Lock

type Lock interface {
	Release(context.Context) error
}

type Locker

type Locker struct {
	Clients []redis.Cmdable
	// contains filtered or unexported fields
}

func (Locker) Acquire

func (l Locker) Acquire(ctx context.Context, key string, ttl time.Duration) (Lock, error)

Acquire will attempt to acquire a lock at the specified key in Redis for the given duration. If it fails to acquire the lock because someone else is already holding it, it will retry until the passed context is canceled. If the context is canceled before the lock is acquired it will return the context error. It may also return other errors if it cannot communicate with Redis.

Note: it is critical that the caller controls the blocking time by passing in a context that is cancelable or which has a deadline. If the context is never canceled and the lock cannot be acquired, the function will never return.

func (Locker) Prepare

func (l Locker) Prepare(ctx context.Context) error

Prepare preloads any Lua scripts needed by locker. This allows later commands to use EVALSHA rather than straight EVAL. Calling Prepare is optional but recommended.

func (Locker) TryAcquire

func (l Locker) TryAcquire(ctx context.Context, key string, ttl time.Duration) (Lock, error)

TryAcquire attempts to acquire a lock at the specified key in Redis for the given duration. If it fails to acquire the lock because someone else is already holding it, it will return ErrLockNotAcquired. It may also return other errors if it cannot communicate with Redis.

Jump to

Keyboard shortcuts

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