-
Notifications
You must be signed in to change notification settings - Fork 42
/
lock.go
251 lines (235 loc) · 6.65 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
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
243
244
245
246
247
248
249
250
251
// Copyright 2021 gotomicro
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package rlock
import (
"context"
_ "embed"
"errors"
"fmt"
"github.com/redis/go-redis/v9"
"sync"
"time"
"github.com/google/uuid"
"golang.org/x/sync/singleflight"
)
var (
//go:embed script/lua/unlock.lua
luaUnlock string
//go:embed script/lua/refresh.lua
luaRefresh string
//go:embed script/lua/lock.lua
luaLock string
ErrFailedToPreemptLock = errors.New("rlock: 抢锁失败")
// ErrLockNotHold 一般是出现在你预期你本来持有锁,结果却没有持有锁的地方
// 比如说当你尝试释放锁的时候,可能得到这个错误
// 这一般意味着有人绕开了 rlock 的控制,直接操作了 Redis
ErrLockNotHold = errors.New("rlock: 未持有锁")
)
type Client struct {
client redis.Cmdable
g singleflight.Group
// valuer 用于生成值,将来可以考虑暴露出去允许用户自定义
valuer func() string
}
func NewClient(client redis.Cmdable) *Client {
return &Client{
client: client,
valuer: func() string {
return uuid.New().String()
},
}
}
func (c *Client) SingleflightLock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error) {
for {
flag := false
result := c.g.DoChan(key, func() (interface{}, error) {
flag = true
return c.Lock(ctx, key, expiration, retry, timeout)
})
select {
case res := <-result:
if flag {
c.g.Forget(key)
if res.Err != nil {
return nil, res.Err
}
return res.Val.(*Lock), nil
}
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
// Lock 是尽可能重试减少加锁失败的可能
// Lock 会在超时或者锁正被人持有的时候进行重试
// 最后返回的 error 使用 errors.Is 判断,可能是:
// - context.DeadlineExceeded: Lock 整体调用超时
// - ErrFailedToPreemptLock: 超过重试次数,但是整个重试过程都没有出现错误
// - DeadlineExceeded 和 ErrFailedToPreemptLock: 超过重试次数,但是最后一次重试超时了
// 你在使用的过程中,应该注意:
// - 如果 errors.Is(err, context.DeadlineExceeded) 那么最终有没有加锁成功,谁也不知道
// - 如果 errors.Is(err, ErrFailedToPreemptLock) 说明肯定没成功,而且超过了重试次数
// - 否则,和 Redis 通信出了问题
func (c *Client) Lock(ctx context.Context, key string, expiration time.Duration, retry RetryStrategy, timeout time.Duration) (*Lock, error) {
val := c.valuer()
var timer *time.Timer
defer func() {
if timer != nil {
timer.Stop()
}
}()
for {
lctx, cancel := context.WithTimeout(ctx, timeout)
res, err := c.client.Eval(lctx, luaLock, []string{key}, val, expiration.Seconds()).Result()
cancel()
if err != nil && !errors.Is(err, context.DeadlineExceeded) {
// 非超时错误,那么基本上代表遇到了一些不可挽回的场景,所以没太大必要继续尝试了
// 比如说 Redis server 崩了,或者 EOF 了
return nil, err
}
if res == "OK" {
return newLock(c.client, key, val, expiration), nil
}
interval, ok := retry.Next()
if !ok {
if err != nil {
err = fmt.Errorf("最后一次重试错误: %w", err)
} else {
err = fmt.Errorf("锁被人持有: %w", ErrFailedToPreemptLock)
}
return nil, fmt.Errorf("rlock: 重试机会耗尽,%w", err)
}
if timer == nil {
timer = time.NewTimer(interval)
} else {
timer.Reset(interval)
}
select {
case <-timer.C:
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
func (c *Client) TryLock(ctx context.Context,
key string, expiration time.Duration) (*Lock, error) {
val := c.valuer()
ok, err := c.client.SetNX(ctx, key, val, expiration).Result()
if err != nil {
// 网络问题,服务器问题,或者超时,都会走过来这里
return nil, err
}
if !ok {
// 已经有人加锁了,或者刚好和人一起加锁,但是自己竞争失败了
return nil, ErrFailedToPreemptLock
}
return newLock(c.client, key, val, expiration), nil
}
type Lock struct {
client redis.Cmdable
key string
value string
expiration time.Duration
unlock chan struct{}
signalUnlockOnce sync.Once
}
func newLock(client redis.Cmdable, key string, value string, expiration time.Duration) *Lock {
return &Lock{
client: client,
key: key,
value: value,
expiration: expiration,
unlock: make(chan struct{}, 1),
}
}
func (l *Lock) AutoRefresh(interval time.Duration, timeout time.Duration) error {
ticker := time.NewTicker(interval)
// 刷新超时 channel
ch := make(chan struct{}, 1)
defer func() {
ticker.Stop()
close(ch)
}()
for {
select {
case <-ticker.C:
ctx, cancel := context.WithTimeout(context.Background(), timeout)
err := l.Refresh(ctx)
cancel()
// 超时这里,可以继续尝试
if err == context.DeadlineExceeded {
// 因为有两个可能的地方要写入数据,而 ch
// 容量只有一个,所以如果写不进去就说明前一次调用超时了,并且还没被处理,
// 与此同时计时器也触发了
select {
case ch <- struct{}{}:
default:
}
continue
}
if err != nil {
return err
}
case <-ch:
ctx, cancel := context.WithTimeout(context.Background(), timeout)
err := l.Refresh(ctx)
cancel()
// 超时这里,可以继续尝试
if err == context.DeadlineExceeded {
select {
case ch <- struct{}{}:
default:
}
continue
}
if err != nil {
return err
}
case <-l.unlock:
return nil
}
}
}
func (l *Lock) Refresh(ctx context.Context) error {
res, err := l.client.Eval(ctx, luaRefresh,
[]string{l.key}, l.value, l.expiration.Seconds()).Int64()
if err != nil {
return err
}
if res != 1 {
return ErrLockNotHold
}
return nil
}
// Unlock 解锁
func (l *Lock) Unlock(ctx context.Context) error {
res, err := l.client.Eval(ctx, luaUnlock, []string{l.key}, l.value).Int64()
defer func() {
// 避免重复解锁引起 panic
l.signalUnlockOnce.Do(func() {
l.unlock <- struct{}{}
close(l.unlock)
})
}()
if err == redis.Nil {
return ErrLockNotHold
}
if err != nil {
return err
}
if res != 1 {
return ErrLockNotHold
}
return nil
}