-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
redis_lock.go
89 lines (80 loc) · 2.39 KB
/
redis_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
package cache
import (
"context"
"errors"
"github.com/gomodule/redigo/redis"
)
// ErrLockMismatch is the error if the key is locked by someone else
var ErrLockMismatch = errors.New("key is locked with a different secret")
// lockScript is the locking script
const lockScript = `
local v = redis.call("GET", KEYS[1])
if v == false
then
return redis.call("SET", KEYS[1], ARGV[1], "NX", "EX", ARGV[2]) and 1
else
if v == ARGV[1]
then
return redis.call("SET", KEYS[1], ARGV[1], "EX", ARGV[2]) and 1
else
return 0
end
end
`
// releaseLockScript is the release lock script (removes lock)
const releaseLockScript = `
local v = redis.call("GET",KEYS[1])
if v == false then
return 1
elseif v == ARGV[1] then
return redis.call("DEL",KEYS[1])
else
return 0
end
`
// WriteLock attempts to grab a redis lock
// Creates a new connection and closes connection at end of function call
//
// Custom connections use method: WriteLockRaw()
func WriteLock(ctx context.Context, client *Client, name, secret string, ttl int64) (bool, error) {
conn, err := client.GetConnectionWithContext(ctx)
if err != nil {
return false, err
}
defer client.CloseConnection(conn)
return WriteLockRaw(conn, name, secret, ttl)
}
// WriteLockRaw attempts to grab a redis lock
// Uses existing connection (does not close connection)
func WriteLockRaw(conn redis.Conn, name, secret string, ttl int64) (bool, error) {
script := redis.NewScript(1, lockScript)
if resp, err := redis.Int(script.Do(conn, name, secret, ttl)); err != nil {
return false, err
} else if resp != 0 {
return true, nil
}
return false, ErrLockMismatch
}
// ReleaseLock releases the redis lock
// Creates a new connection and closes connection at end of function call
//
// Custom connections use method: ReleaseLockRaw()
func ReleaseLock(ctx context.Context, client *Client, name, secret string) (bool, error) {
conn, err := client.GetConnectionWithContext(ctx)
if err != nil {
return false, err
}
defer client.CloseConnection(conn)
return ReleaseLockRaw(conn, name, secret)
}
// ReleaseLockRaw releases the redis lock
// Uses existing connection (does not close connection)
func ReleaseLockRaw(conn redis.Conn, name, secret string) (bool, error) {
script := redis.NewScript(1, releaseLockScript)
if resp, err := redis.Int(script.Do(conn, name, secret)); err != nil {
return false, err
} else if resp != 0 {
return true, nil
}
return false, ErrLockMismatch
}