-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
59 lines (50 loc) · 1.18 KB
/
context.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
package watchdog
import (
"context"
"time"
"github.com/redis/go-redis/v9"
)
var (
lockScript = redis.NewScript(`
if redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then
return 1
else
if redis.call("GET", KEYS[1]) == ARGV[1] then
if redis.call("PEXPIRE", KEYS[1], ARGV[2]) then
return 1
else
return 0
end
else
return 0
end
end`)
unlockScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end`)
expireScript = redis.NewScript(`
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("PEXPIRE", KEYS[1], ARGV[2])
else
return 0
end`)
)
type ctx struct {
ctx context.Context
client *redis.Client
key string
val string
expireDuration time.Duration
}
func (c *ctx) Lock() (bool, error) {
return lockScript.Run(c.ctx, c.client, []string{c.key}, c.val, c.expireDuration.Milliseconds()).Bool()
}
func (c *ctx) Unlock() (bool, error) {
return unlockScript.Run(c.ctx, c.client, []string{c.key}, c.val).Bool()
}
func (c *ctx) Expire() error {
return expireScript.Run(c.ctx, c.client, []string{c.key}, c.val, c.expireDuration.Milliseconds()).Err()
}