-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathredis.go
More file actions
74 lines (62 loc) · 1.34 KB
/
redis.go
File metadata and controls
74 lines (62 loc) · 1.34 KB
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
package redislock
import (
"context"
"fmt"
"github.com/go-redis/redis/v8"
"sync"
"time"
)
type RedisLock struct {
context.Context
*redis.Client
key string
token string
lockTimeout time.Duration
isAutoRenew bool
autoRenewCtx context.Context
autoRenewCancel context.CancelFunc
mutex sync.Mutex
}
// 默认锁超时时间
const lockTime = 5 * time.Second
type Option func(lock *RedisLock)
func New(ctx context.Context, redisClient *redis.Client, lockKey string, options ...Option) *RedisLock {
lock := &RedisLock{
Context: ctx,
Client: redisClient,
lockTimeout: lockTime,
}
for _, f := range options {
f(lock)
}
lock.key = lockKey
// token 自动生成
if lock.token == "" {
lock.token = fmt.Sprintf("token_%d", time.Now().UnixNano())
}
return lock
}
// WithKey 设置锁的key
func WithKey(key string) Option {
return func(lock *RedisLock) {
lock.key = key
}
}
// 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
}
}