-
Notifications
You must be signed in to change notification settings - Fork 8
/
lock.go
75 lines (66 loc) · 1.43 KB
/
lock.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package go_redislock
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"time"
)
type RedisLockInter interface {
// Lock 加锁
Lock() error
// SpinLock 自旋锁
SpinLock(timeout time.Duration) error
// UnLock 解锁
UnLock() error
// Renew 手动续期
Renew() error
}
type RedisInter interface {
redis.Scripter
}
type RedisLock struct {
context.Context
redis RedisInter
key string
token string
lockTimeout time.Duration
isAutoRenew bool
autoRenewCtx context.Context
autoRenewCancel context.CancelFunc
}
type Option func(lock *RedisLock)
func New(ctx context.Context, redisClient RedisInter, lockKey string, options ...Option) RedisLockInter {
lock := &RedisLock{
Context: ctx,
redis: redisClient,
lockTimeout: lockTime,
}
for _, f := range options {
f(lock)
}
lock.key = lockKey
// automatically generate tokens
if lock.token == "" {
lock.token = fmt.Sprintf("lock_token:%s", uuid.New().String())
}
return lock
}
// WithTimeout 设置锁过期时间
func WithTimeout(timeout time.Duration) Option {
return func(lock *RedisLock) {
lock.lockTimeout = timeout
}
}
// WithAutoRenew 是否开启自动续期
func WithAutoRenew() Option {
return func(lock *RedisLock) {
lock.isAutoRenew = true
}
}
// WithToken 设置锁的Token
func WithToken(token string) Option {
return func(lock *RedisLock) {
lock.token = token
}
}