-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
83 lines (66 loc) · 1.53 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
package looper
import (
"context"
"fmt"
"time"
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v9"
"github.com/redis/go-redis/v9"
)
// redisOptions := &redis.Options{
// Addr: conf.Redis.Host,
// }
//
// redisClient := redis.NewClient(redisOptions)
//
// looperRedis, err := looper.RedisLocker(ctx, redisClient)
// if err != nil {
// return err
// }
// RedisLocker provides an implementation of the Locker interface using
// redis for storage.
func RedisLocker(ctx context.Context, rc redis.UniversalClient) (locker, error) {
err := rc.Ping(ctx).Err()
if err != nil {
return nil, fmt.Errorf("%s: %w", ErrFailedToConnectToLocker, err)
}
pool := goredis.NewPool(rc)
rs := redsync.New(pool)
l := redisLocker{rs: rs}
return &l, nil
}
// Locker
var _ locker = (*redisLocker)(nil)
type redisLocker struct {
rs *redsync.Redsync
}
func (r *redisLocker) lock(ctx context.Context, key string, timeout time.Duration) (lock, error) {
options := []redsync.Option{
redsync.WithTries(1),
redsync.WithExpiry(timeout + time.Second),
}
mu := r.rs.NewMutex(key, options...)
err := mu.LockContext(ctx)
if err != nil {
return nil, ErrFailedToObtainLock
}
rl := &redisLock{
mu: mu,
}
return rl, nil
}
// Lock
var _ lock = (*redisLock)(nil)
type redisLock struct {
mu *redsync.Mutex
}
func (r *redisLock) unlock(ctx context.Context) error {
unlocked, err := r.mu.UnlockContext(ctx)
if err != nil {
return ErrFailedToReleaseLock
}
if !unlocked {
return ErrFailedToReleaseLock
}
return nil
}