forked from jefferyjob/go-redislock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock_lua.go
68 lines (58 loc) · 1.67 KB
/
lock_lua.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
package go_redislock
const (
// 加锁
lockScript = `
local lock_key = KEYS[1]
local lock_value = ARGV[1]
local lock_ttl = tonumber(ARGV[2])
local reentrant_key = lock_key .. ':count:' .. lock_value
local reentrant_count = tonumber(redis.call('GET', reentrant_key) or '0')
if reentrant_count > 0 then
redis.call('INCR', reentrant_key)
redis.call('EXPIRE', lock_key, lock_ttl)
redis.call('EXPIRE', reentrant_key, lock_ttl)
return "OK"
end
if redis.call('SET', lock_key, lock_value, 'NX', 'EX', lock_ttl) then
redis.call('SET', reentrant_key, 1)
redis.call('EXPIRE', reentrant_key, lock_ttl)
return "OK"
end
return nil
`
// 解锁
unLockScript = `
local lock_key = KEYS[1]
local lock_value = ARGV[1]
local reentrant_key = lock_key .. ':count:' .. lock_value
local reentrant_count = tonumber(redis.call('GET', reentrant_key) or '0')
if reentrant_count > 1 then
redis.call('DECR', reentrant_key)
return "OK"
elseif reentrant_count == 1 then
redis.call('DEL', reentrant_key)
redis.call('DEL', lock_key)
return "OK"
end
if redis.call('GET', lock_key) == lock_value then
redis.call('DEL', lock_key)
return "OK"
else
return nil
end
`
// 续期
renewScript = `
local lock_key = KEYS[1]
local lock_value = ARGV[1]
local lock_ttl = tonumber(ARGV[2])
local reentrant_key = lock_key .. ':count:' .. lock_value
local reentrant_count = tonumber(redis.call('GET', reentrant_key) or '0')
if reentrant_count > 0 or redis.call('GET', lock_key) == lock_value then
redis.call('EXPIRE', lock_key, lock_ttl)
redis.call('EXPIRE', reentrant_key, lock_ttl)
return "OK"
end
return nil
`
)