redis_lock

package
v0.0.0-...-f6ff08b Latest Latest
Warning

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

Go to latest
Published: Jun 30, 2023 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrFailedToPreemptLock = errors.New("redis_lock: 抢锁失败")
	// ErrLockNotHold 一般是出现在你预期你本来持有锁,结果却没有持有锁的地方
	// 比如说当你尝试释放锁的时候,可能得到这个错误
	// 这一般意味着有人绕开了 rlock 的控制,直接操作了 Redis
	ErrLockNotHold = errors.New("rlock: 未持有锁")
)

Functions

This section is empty.

Types

type Client

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

Client singleflight.Group SingleFlight的作用是在处理多个goroutine同时调用同一个函数的时候,只让一个goroutine去实际调用这个函数, 等到这个goroutine返回结果的时候,再把结果返回给其他几个同时调用了相同函数的goroutine,这样可以减少并发调用的数量

func NewClient

func NewClient(client redis.Cmdable) *Client

func (*Client) Lock

func (c *Client) Lock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error)

Lock 是尽可能重试减少加锁失败的可能 Lock 会在超时或者锁正被人持有的时候进行重试 最后返回的 error 使用 errors.Is 判断,可能是: - context.DeadlineExceeded: Lock 整体调用超时 - ErrFailedToPreemptLock: 超过重试次数,但是整个重试过程都没有出现错误 - DeadlineExceeded 和 ErrFailedToPreemptLock: 超过重试次数,但是最后一次重试超时了 你在使用的过程中,应该注意: - 如果 errors.Is(err, context.DeadlineExceeded) 那么最终有没有加锁成功,谁也不知道 - 如果 errors.Is(err, ErrFailedToPreemptLock) 说明肯定没成功,而且超过了重试次数 - 否则,和 Redis 通信出了问题

func (*Client) SingleflightLock

func (c *Client) SingleflightLock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error)

SingleflightLock 是对 Lock 的封装,使用 singleflight 来减少对 Redis 的压力

func (*Client) TryLock

func (c *Client) TryLock(ctx context.Context, key string, expiration time.Duration) (*Lock, error)

type FixIntervalRetry

type FixIntervalRetry struct {
	// 重试间隔
	Interval time.Duration
	// 最大次数
	Max int
	// contains filtered or unexported fields
}

func (*FixIntervalRetry) Next

func (f *FixIntervalRetry) Next() (time.Duration, bool)

type Lock

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

func (*Lock) AutoRefresh

func (l *Lock) AutoRefresh(interval time.Duration, timeout time.Duration) error

func (*Lock) Refresh

func (l *Lock) Refresh(ctx context.Context) error

func (*Lock) Unlock

func (l *Lock) Unlock(ctx context.Context) error

Unlock 解锁

type RetryStrategy

type RetryStrategy interface {
	// Next 返回下一次重试的间隔,如果不需要继续重试,那么第二参数发挥 false
	Next() (time.Duration, bool)
}

Jump to

Keyboard shortcuts

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