-
Notifications
You must be signed in to change notification settings - Fork 0
/
redis.go
53 lines (45 loc) · 958 Bytes
/
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
package lock
import (
"context"
"errors"
"time"
"github.com/go-redis/redis/v8"
)
type RedisLocker struct {
key string
client *redis.Client
}
func NewRedisLocker(client *redis.Client) *RedisLocker {
return &RedisLocker{
key: lockKey,
client: client,
}
}
func (l *RedisLocker) GetLock(ctx context.Context, timeout time.Duration) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
result, err := l.client.SetNX(ctx, l.key, locked, -1).Result()
if err != nil {
cancel()
return err
}
if !result {
cancel()
return errors.New("failed to lock")
}
return nil
}
func (l *RedisLocker) HasLock(ctx context.Context) (bool, error) {
_, err := l.client.Get(ctx, l.key).Result()
if err != nil {
if err == redis.Nil {
return false, nil
}
return false, err
}
return true, nil
}
func (l *RedisLocker) ReleaseLock(ctx context.Context) error {
_, err := l.client.Del(ctx, l.key).Result()
return err
}