-
Notifications
You must be signed in to change notification settings - Fork 1
/
lock.go
99 lines (83 loc) · 2.23 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
package vcache
import (
"errors"
"time"
)
const (
CLOCK_PREFIX = "clock:"
SLOCK_PREFIX = "slock:"
)
// CLock is a concurrent lock, it will lock the key in lockSecond secoend and expire in expireSecond
// When CLock the same key in lockSecond, it will extend the lock time to keep it exclusive in concurrent env.
func (this *VCache) CLock(key string, lockSecond, expireSecond int) (ok bool, err error) {
rc, err := RedisPool.Get()
if err != nil {
return
}
defer RedisPool.CarefullyPut(rc, &err)
if lockSecond > expireSecond {
err = errors.New("lockedSecond should not greater than expireSecond")
return
}
key = this.GetKey(CLOCK_PREFIX + key)
curTime := int(time.Now().Unix())
expireTime := curTime + lockSecond + 1
rs, err := rc.Conn.Cmd("SETNX", key, expireTime).Int()
if err != nil {
return
}
if rs == 1 {
err = rc.Conn.Cmd("EXPIRE", key, expireSecond).Err
ok = true
return
}
lockTime, _ := rc.Conn.Cmd("GET", key).Int()
oldLockTime, _ := rc.Conn.Cmd("GETSET", key, expireTime).Int()
rc.Conn.Cmd("EXPIRE", key, expireSecond)
if curTime > lockTime && curTime > oldLockTime {
ok = true
return
}
return
}
// SLock is a sequencial lock, it will lock the key in lockSecond, just like a normal lock.
func (this *VCache) SLock(key string, lockSecond int) (ok bool, err error) {
rc, err := RedisPool.Get()
if err != nil {
return
}
defer RedisPool.CarefullyPut(rc, &err)
key = this.GetKey(SLOCK_PREFIX + key)
// when is not locked, it will return string OK
ok, _ = rc.Conn.Cmd("SET", key, 1, "EX", lockSecond, "NX").Bool()
return
}
// UnCLock will unlock CLock
func (this *VCache) UnCLock(key string) (err error) {
rc, err := RedisPool.Get()
if err != nil {
return
}
defer RedisPool.CarefullyPut(rc, &err)
key = this.GetKey(CLOCK_PREFIX + key)
curTime := int(time.Now().Unix())
lockTime, err := rc.Conn.Cmd("GET", key).Int()
if err != nil || lockTime == 0 {
return
}
if curTime < lockTime {
err = rc.Conn.Cmd("DEL", key).Err
}
return
}
// UnSLock will unlock SLock
func (this *VCache) UnSLock(key string) (err error) {
rc, err := RedisPool.Get()
if err != nil {
return
}
defer RedisPool.CarefullyPut(rc, &err)
key = this.GetKey(SLOCK_PREFIX + key)
err = rc.Conn.Cmd("DEL", key).Err
return
}