Documentation ¶
Overview ¶
Example ¶
// Connect to Redis client := redis.NewClient(&redis.Options{ Network: "tcp", Addr: "127.0.0.1:6379", }) defer client.Close() // Create a new locker with default settings locker := lock.New(client, "lock.foo", nil) // Try to obtain lock hasLock, err := locker.Lock() if err != nil { panic(err.Error()) } else if !hasLock { fmt.Println("could not obtain lock!") return } // Don't forget to defer Unlock! defer locker.Unlock() fmt.Println("I have a lock!") // Sleep and check if still locked afterwards. time.Sleep(200 * time.Millisecond) if locker.IsLocked() { fmt.Println("My lock has expired!") } // Renew your lock renewed, err := locker.Lock() if err != nil { panic(err.Error()) } else if !renewed { fmt.Println("could not renew lock!") return } fmt.Println("I have renewed my lock!")
Output: I have a lock! My lock has expired! I have renewed my lock!
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrLockNotObtained = errors.New("lock not obtained")
ErrLockNotObtained may be returned by Obtain() and Run() if a lock could not be obtained.
Functions ¶
Types ¶
type Locker ¶
type Locker struct {
// contains filtered or unexported fields
}
Locker allows (repeated) distributed locking.
func New ¶
func New(client RedisClient, key string, opts *Options) *Locker
New creates a new distributed locker on a given key.
func Obtain ¶
func Obtain(client RedisClient, key string, opts *Options) (*Locker, error)
Obtain is a shortcut for New().Lock(). It may return ErrLockNotObtained if a lock was not successfully acquired.
func (*Locker) Lock ¶
Lock applies the lock, don't forget to defer the Unlock() function to release the lock after usage.
func (*Locker) LockWithContext ¶
LockWithContext is like Lock but allows to pass an additional context which allows cancelling lock attempts prematurely.
type Options ¶
type Options struct { // The maximum duration to lock a key for // Default: 5s LockTimeout time.Duration // The number of time the acquisition of a lock will be retried. // Default: 0 = do not retry RetryCount int // RetryDelay is the amount of time to wait between retries. // Default: 100ms RetryDelay time.Duration }
Options describe the options for the lock
type RedisClient ¶
type RedisClient interface { SetNX(key string, value interface{}, expiration time.Duration) *redis.BoolCmd Eval(script string, keys []string, args ...interface{}) *redis.Cmd EvalSha(sha1 string, keys []string, args ...interface{}) *redis.Cmd ScriptExists(scripts ...string) *redis.BoolSliceCmd ScriptLoad(script string) *redis.StringCmd }
RedisClient is a minimal client interface.
Click to show internal directories.
Click to hide internal directories.