-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredislock.go
242 lines (199 loc) · 4.9 KB
/
redislock.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package corgi
import (
"context"
"fmt"
"os"
"sync"
"time"
redisLib "github.com/go-redis/redis/v8"
)
type Locker interface {
// TryLock 尝试获取锁
TryLock(ctx context.Context, key string) bool
// Unlock 释放锁
Unlock(ctx context.Context, key string) bool
}
type redisDriver struct {
client *redisLib.Client
clusterClient *redisLib.ClusterClient
}
var _ Locker = (*redisDriver)(nil)
var (
lockDriver = &redisDriver{}
pingTimeout = time.Second * 3
doOnce = &sync.Once{}
)
// SetRedisProviderStandalone 设置redis连接配置(standalone)
func SetRedisProviderStandalone(opt *redisLib.Options) {
doOnce.Do(func() {
initClient(opt)
})
}
// SetRedisProviderCluster 设置redis连接配置(cluster)
func SetRedisProviderCluster(opt *redisLib.ClusterOptions) {
doOnce.Do(func() {
initClusterClient(opt)
})
}
// SetRedisProviderFailOver 设置redis连接配置(fail-over)
func SetRedisProviderFailOver(opt *redisLib.FailoverOptions) {
doOnce.Do(func() {
initFailOverClient(opt)
})
}
// SetRedisProviderClient 设置redis连接实例(单实例)
func SetRedisProviderClient(client *redisLib.Client) {
doOnce.Do(func() {
lockDriver.client = client
})
}
// SetRedisProviderClusterClient 设置redis连接实例(cluster集群)
func SetRedisProviderClusterClient(client *redisLib.ClusterClient) {
doOnce.Do(func() {
lockDriver.clusterClient = client
})
}
func initClient(opt *redisLib.Options) {
rdb := redisLib.NewClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
err := rdb.Ping(ctx).Err()
if err != nil {
panic(err)
}
cancel()
lockDriver.client = rdb
}
func initClusterClient(opt *redisLib.ClusterOptions) {
rdb := redisLib.NewClusterClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
err := rdb.Ping(ctx).Err()
if err != nil {
panic(err)
}
cancel()
lockDriver.clusterClient = rdb
}
func initFailOverClient(opt *redisLib.FailoverOptions) {
rdb := redisLib.NewFailoverClient(opt)
ctx, cancel := context.WithTimeout(context.Background(), pingTimeout)
err := rdb.Ping(ctx).Err()
if err != nil {
panic(err)
}
cancel()
lockDriver.client = rdb
}
type stateListeners struct {
mux *sync.Mutex
listeners map[string]chan struct{}
}
var (
lockTTL = time.Second * 10
redisExecuteTimeout = time.Second * 3
renewalCheckInterval = time.Second * 1
states = &stateListeners{mux: &sync.Mutex{}, listeners: make(map[string]chan struct{})}
)
// Wakeup 启动
func Wakeup() Locker {
return lockDriver
}
// Asleep 释放redis连接
func Asleep() {
if lockDriver.client != nil {
_ = lockDriver.client.Close()
}
if lockDriver.clusterClient != nil {
_ = lockDriver.clusterClient.Close()
}
}
func (rd *redisDriver) TryLock(ctx context.Context, key string) bool {
if rd.client == nil && rd.clusterClient == nil {
return false
}
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
cwt, cancel := context.WithTimeout(ctx, redisExecuteTimeout)
defer cancel()
ctx = cwt
}
var (
ok bool
err error
)
if rd.client != nil {
ok, err = rd.client.SetNX(ctx, key, lockerValue(), lockTTL).Result()
}
if rd.clusterClient != nil {
ok, err = rd.clusterClient.SetNX(ctx, key, lockerValue(), lockTTL).Result()
}
if err != nil {
return false
}
if ok {
cancelChan := make(chan struct{})
//自动续期
go func() {
ticker := time.NewTicker(renewalCheckInterval)
innerCtx := context.Background()
defer ticker.Stop()
LOOP:
for {
select {
case <-ticker.C:
if rd.client != nil {
if redisOK, redisErr := rd.client.Expire(innerCtx, key, lockTTL).Result(); !redisOK || redisErr != nil {
break LOOP
}
}
if rd.clusterClient != nil {
if redisOK, redisErr := rd.clusterClient.Expire(innerCtx, key, lockTTL).Result(); !redisOK || redisErr != nil {
break LOOP
}
}
case <-cancelChan:
break LOOP
}
}
}()
states.mux.Lock()
states.listeners[key] = cancelChan
states.mux.Unlock()
}
return ok
}
func (rd *redisDriver) Unlock(ctx context.Context, key string) bool {
if rd.client == nil && rd.clusterClient == nil {
return false
}
if _, hasDeadline := ctx.Deadline(); !hasDeadline {
cwt, cancel := context.WithTimeout(ctx, redisExecuteTimeout)
defer cancel()
ctx = cwt
}
if rd.client != nil {
cnt, err := rd.client.Del(ctx, key).Result()
return cnt > 0 && err == nil
}
if rd.clusterClient != nil {
cnt, err := rd.clusterClient.Del(ctx, key).Result()
return cnt > 0 && err == nil
}
go func() {
states.mux.Lock()
ch, ok := states.listeners[key]
if ok {
delete(states.listeners, key)
}
states.mux.Unlock()
if ok {
ch <- struct{}{}
close(ch)
}
}()
return false
}
// 锁的持有者信息
func lockerValue() string {
hostname, _ := os.Hostname()
ip, _ := GetLocalIP()
return fmt.Sprintf("lockedAt:%s@%s(%s)", time.Now().Format("2006-01-02T15:04:05Z"), hostname, ip)
}