/
redis_locker.go
117 lines (94 loc) · 2.04 KB
/
redis_locker.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
package qmq
import (
"crypto/rand"
"encoding/base64"
mrand "math/rand"
"sync"
"sync/atomic"
"time"
)
type RedisLocker struct {
id string
token string
conn *RedisConnection
mutex sync.Mutex
isLocked atomic.Bool
unlockCh chan interface{}
}
func NewRedisLocker(id string, conn *RedisConnection) *RedisLocker {
return &RedisLocker{
id: id,
token: "",
conn: conn,
unlockCh: make(chan interface{}),
}
}
func (l *RedisLocker) TryLockWithTimeout(timeoutMs int64) bool {
randomBytes := make([]byte, 8)
_, err := rand.Read(randomBytes)
if err != nil {
return false
}
l.token = base64.StdEncoding.EncodeToString(randomBytes)
writeRequest := NewWriteRequest(&String{Value: l.token})
result, err := l.conn.TempSet(l.id, writeRequest, timeoutMs)
if err != nil {
return false
}
return result
}
func (l *RedisLocker) TryLock() bool {
return l.TryLockWithTimeout(10000)
}
func (l *RedisLocker) Lock() {
l.mutex.Lock()
for !l.TryLock() {
time.Sleep(time.Duration(mrand.Intn(95)+5) * time.Millisecond)
}
l.isLocked.Store(true)
go l.UpdateExpiryTimeout(10000)
}
func (l *RedisLocker) LockWithTimeout(timeoutMs int64) {
l.mutex.Lock()
for !l.TryLockWithTimeout(timeoutMs) {
time.Sleep(time.Duration(mrand.Intn(95)+5) * time.Millisecond)
}
l.isLocked.Store(true)
go l.UpdateExpiryTimeout(timeoutMs)
}
func (l *RedisLocker) Unlock() {
if l.isLocked.CompareAndSwap(true, false) {
defer func() {
l.unlockCh <- nil
l.mutex.Unlock()
}()
}
readRequest, err := l.conn.Get(l.id)
if err != nil {
return
}
token := String{}
err = readRequest.Data.UnmarshalTo(&token)
if err != nil {
return
}
if l.token != token.Value {
return
}
l.conn.Unset(l.id)
}
func (l *RedisLocker) IsLocked() bool {
return l.isLocked.Load()
}
func (l *RedisLocker) UpdateExpiryTimeout(timeoutMs int64) {
l.conn.WgAdd()
defer l.conn.WgDone()
for {
select {
case <-l.unlockCh:
return
case <-time.After(time.Duration(timeoutMs/2) * time.Millisecond):
l.conn.TempUpdateExpiry(l.id, timeoutMs)
}
}
}