-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathredis.go
89 lines (75 loc) · 1.63 KB
/
redis.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 distlock
import (
"fmt"
"time"
"github.com/gomodule/redigo/redis"
)
const (
unlockScript = `
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
else
return 0
end
`
)
// RedisPool represents a pool of redis connections.
type RedisPool interface {
// Get returns a connection from the pool.
Get() redis.Conn
}
type redisProvider struct {
pool RedisPool
}
func NewRedisProvider(redisPool RedisPool) (Provider, error) {
return &redisProvider{
pool: redisPool,
}, nil
}
func (p *redisProvider) Name() string {
return "redis"
}
func (p *redisProvider) Lock(lock NamedLock) error {
conn := p.pool.Get()
defer conn.Close()
var (
reply interface{}
err error
)
lifetime := lock.GetLifetime()
if lifetime > 0 {
// SET key value PX milliseconds NX
// PX: Set the specified expire time, in milliseconds.
// NX: Only set the key if it does not already exist.
reply, err = conn.Do(
"SET", lock.GetId(), lock.GetOwner(),
"PX", lock.GetLifetime().Nanoseconds()/int64(time.Millisecond),
"NX",
)
} else { // never expire
reply, err = conn.Do(
"SET", lock.GetId(), lock.GetOwner(),
"NX",
)
}
if err != nil {
return fmt.Errorf("redis SET: %w", err)
}
if v, ok := reply.(string); ok && v == "OK" {
return nil
}
return ErrAlreadyLocked
}
func (p *redisProvider) Unlock(lock NamedLock) error {
conn := p.pool.Get()
defer conn.Close()
command := redis.NewScript(1, unlockScript)
ret, err := redis.Int(command.Do(conn, lock.GetId(), lock.GetOwner()))
if err != nil {
return fmt.Errorf("redis EVAL: %w", err)
}
if ret == 0 {
return ErrNotLocked
}
return nil
}