multiredsync

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2024 License: MIT Imports: 9 Imported by: 0

README

multiredsync

批量版本的 redsync,可以针对一批分布式锁进行Lock/Unlock

Features

  1. 支持一次性对多个key进行加锁,操作具有原子性(任一未上锁成功则会阻塞等待)
  2. 拥有和 redsync 相同的使用方式,仅构造方法有锁差异
  3. 当仅对一个key加锁时,会退化为与 redsync 相同的操作过程(redlock),完全兼容 redsync 的使用场景&性能

Usage

除了初始化方案需要传入多个key以外,其他的使用方式与redsync无二

func main() {
    opt := &redis.Options{
        Addr:     "127.0.0.1:6379",
    }
    client := redis.NewClient(opt)
    redsync := multiredsync.New(goredis.NewPool(client))
	
    mutex := redsync.NewMutex(
        []string{"key1", "key2", "key3", "key4", "key4"},
        multiredsync.WithExpiry(8*time.Second),
        multiredsync.WithRetryDelay(100*time.Millisecond),
    )
	
    if err := mutex.Lock(); err != nil {
        panic(err)
    }

    if ok, err := mutex.Unlock(); !ok || err != nil {
        panic("unlock failed")
    }
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrExtendFailed = errors.New("redsync: failed to extend lock")

ErrExtendFailed is the error resulting if Redsync fails to extend the lock.

View Source
var ErrFailed = errors.New("redsync: failed to acquire lock")

ErrFailed is the error resulting if Redsync fails to acquire the lock after exhausting all retries.

View Source
var ErrLockAlreadyExpired = errors.New("redsync: failed to unlock, lock was already expired")

ErrLockAlreadyExpired is the error resulting if trying to unlock the lock which already expired.

Functions

This section is empty.

Types

type DelayFunc

type DelayFunc func(tries int) time.Duration

A DelayFunc is used to decide the amount of time to wait between retries.

type ErrNodeTaken

type ErrNodeTaken struct {
	Node int
}

ErrNodeTaken is the error resulting if the lock is already taken in one of the cluster's nodes

func (ErrNodeTaken) Error

func (err ErrNodeTaken) Error() string

type ErrTaken

type ErrTaken struct {
	Nodes []int
}

ErrTaken happens when the lock is already taken in a quorum on nodes.

func (ErrTaken) Error

func (err ErrTaken) Error() string

type MultiRedsync

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

MultiRedsync provides a simple method for creating distributed mutexes using multiple Redis connection pools.

func New

func New(pools ...redis.Pool) *MultiRedsync

New creates and returns a new MultiRedsync instance from given Redis connection pools.

func (*MultiRedsync) NewMutex

func (r *MultiRedsync) NewMutex(names []string, options ...Option) *Mutex

NewMutex returns a new distributed mutex with given name.

type Mutex

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

A Mutex is a distributed mutual exclusion lock.

func (*Mutex) Extend

func (m *Mutex) Extend() (bool, error)

Extend resets the mutex's expiry and returns the status of expiry extension.

func (*Mutex) ExtendContext

func (m *Mutex) ExtendContext(ctx context.Context) (bool, error)

ExtendContext resets the mutex's expiry and returns the status of expiry extension.

func (*Mutex) Lock

func (m *Mutex) Lock() error

Lock locks m. In case it returns an error on failure, you may retry to acquire the lock by calling this method again.

func (*Mutex) LockContext

func (m *Mutex) LockContext(ctx context.Context) error

LockContext locks m. In case it returns an error on failure, you may retry to acquire the lock by calling this method again.

func (*Mutex) Names

func (m *Mutex) Names() []string

Names returns mutex names (i.e. the Redis key).

func (*Mutex) TryLock

func (m *Mutex) TryLock() error

TryLock only attempts to lock m once and returns immediately regardless of success or failure without retrying.

func (*Mutex) TryLockContext

func (m *Mutex) TryLockContext(ctx context.Context) error

TryLockContext only attempts to lock m once and returns immediately regardless of success or failure without retrying.

func (*Mutex) Unlock

func (m *Mutex) Unlock() (bool, error)

Unlock unlocks m and returns the status of unlock.

func (*Mutex) UnlockContext

func (m *Mutex) UnlockContext(ctx context.Context) (bool, error)

UnlockContext unlocks m and returns the status of unlock.

func (*Mutex) Until

func (m *Mutex) Until() time.Time

Until returns the time of validity of acquired lock. The value will be zero value until a lock is acquired.

func (*Mutex) Value

func (m *Mutex) Value() string

Value returns the current random value. The value will be empty until a lock is acquired (or WithValue option is used).

type Option

type Option interface {
	Apply(*Mutex)
}

An Option configures a mutex.

func WithDriftFactor

func WithDriftFactor(factor float64) Option

WithDriftFactor can be used to set the clock drift factor. The default value is 0.01.

func WithExpiry

func WithExpiry(expiry time.Duration) Option

WithExpiry can be used to set the expiry of a mutex to the given value. The default is 8s.

func WithFailFast

func WithFailFast(b bool) Option

WithFailFast can be used to quickly acquire and release the lock. When some Redis servers are blocking, we do not need to wait for responses from all the Redis servers response. As long as the quorum is met, we can assume the lock is acquired. The effect of this parameter is to achieve low latency, avoid Redis blocking causing Lock/Unlock to not return for a long time.

func WithGenValueFunc

func WithGenValueFunc(genValueFunc func() (string, error)) Option

WithGenValueFunc can be used to set the custom value generator.

func WithRetryDelay

func WithRetryDelay(delay time.Duration) Option

WithRetryDelay can be used to set the amount of time to wait between retries. The default value is rand(50ms, 250ms).

func WithRetryDelayFunc

func WithRetryDelayFunc(delayFunc DelayFunc) Option

WithRetryDelayFunc can be used to override default delay behavior.

func WithSetNXOnExtend

func WithSetNXOnExtend() Option

WithSetNXOnExtend improves extending logic to extend the key if exist and if not, tries to set a new key in redis Useful if your redises restart often and you want to reduce the chances of losing the lock Read this MR for more info: https://github.com/go-redsync/redsync/pull/149

func WithShufflePools

func WithShufflePools(b bool) Option

WithShufflePools can be used to shuffle Redis pools to reduce centralized access in concurrent scenarios.

func WithTimeoutFactor

func WithTimeoutFactor(factor float64) Option

WithTimeoutFactor can be used to set the timeout factor. The default value is 0.05.

func WithTries

func WithTries(tries int) Option

WithTries can be used to set the number of times lock acquire is attempted. The default value is 32.

func WithValue

func WithValue(v string) Option

WithValue can be used to assign the random value without having to call lock. This allows the ownership of a lock to be "transferred" and allows the lock to be unlocked from elsewhere.

type OptionFunc

type OptionFunc func(*Mutex)

OptionFunc is a function that configures a mutex.

func (OptionFunc) Apply

func (f OptionFunc) Apply(mutex *Mutex)

Apply calls f(mutex)

type RedisError

type RedisError struct {
	Node int
	Err  error
}

A RedisError is an error communicating with one of the Redis nodes.

func (RedisError) Error

func (e RedisError) Error() string

func (RedisError) Unwrap

func (e RedisError) Unwrap() error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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