-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdlock_by_redis.go
More file actions
74 lines (65 loc) · 1.64 KB
/
dlock_by_redis.go
File metadata and controls
74 lines (65 loc) · 1.64 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 distlock
import (
"os"
"time"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
uuid "github.com/satori/go.uuid"
)
const (
_DistributedLock = "pddlock"
/*
-1: failed to get
0: failed to del
1: success to del
*/
_CheckAndDel = `if redis.call('get', KEYS[1]) == ARGV[1] then
return redis.call('del', KEYS[1])
else
return -1
end`
)
// DLockByRedis 通过redis实现的分布式锁
type DLockByRedis struct {
p *RedisConnPool
}
// NewDLockByRedis 获取DLockByRedis实例.
func NewDLockByRedis(p *RedisConnPool) *DLockByRedis {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: time.RFC3339}).With().Caller().Logger()
return &DLockByRedis{
p: p,
}
}
// TryLock 尝试获取分布式锁, 超时后就放弃 (不可重入锁).
func (dlr *DLockByRedis) TryLock(timeoutInSecs int64) (string, bool) {
id := uuid.NewV1().String()
ttr := time.Now().Unix() + timeoutInSecs
for {
// 为了避免出现死锁状态, 需要设置一个合理的过期时间
// TODO: 设置为多少比较合理?
v, err := dlr.p.ExecCommand("SET", _DistributedLock, id, "NX", "EX", 3600)
if err != nil {
log.Error().Err(err).Msg("failed to acquire lock")
return "", false
}
if v == nil {
continue
}
if v.(string) == "OK" {
return id, true
}
if time.Now().Unix() > ttr {
return "", false
}
}
}
// Unlock 释放分布式锁.
func (dlr *DLockByRedis) Unlock(value string) {
v, err := dlr.p.ExecLuaScript(_CheckAndDel, 1, _DistributedLock, value)
if err != nil {
log.Error().Err(err).Msg("failed to release lock")
}
if v == nil || v.(int64) != 1 {
log.Error().Err(err).Msg("failed to release lock")
}
}