This repository has been archived by the owner on Oct 31, 2021. It is now read-only.
/
redis-mutex.go
92 lines (70 loc) · 1.88 KB
/
redis-mutex.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
90
91
92
package redismutex
import (
"context"
"fmt"
"github.com/covid19cz/erouska-backend/internal/logging"
redisclient "github.com/go-redis/redis/v8"
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v8"
"os"
"sync"
"time"
)
var rs *Connection
var ctx context.Context
type lazyConnection func() *redsync.Redsync
//Connection Contains lazy Redsync connection
type Connection struct {
inner lazyConnection
}
func init() {
ctx = context.Background()
connect := func() *redsync.Redsync {
logger := logging.FromContext(ctx).Named("efgs.redis-mutex.connect")
logger.Debug("Connecting to EFGS Redis")
addr, ok := os.LookupEnv("EFGS_REDIS_ADDR")
if !ok {
panic("EFGS_REDIS_ADDR env missing")
}
client := redisclient.NewClient(&redisclient.Options{
Addr: addr,
DB: 1, // here it differs from normal Redis client!
})
_, err := client.Ping(ctx).Result()
if err != nil {
err := fmt.Errorf("Connection to Redis failed:%v", err)
logger.Error(err)
panic(err)
}
logger.Debugf("Connected to EFGS Redis at %v", addr)
return redsync.New(goredis.NewPool(client))
}
var conn *redsync.Redsync
var once sync.Once
initInner := func() *redsync.Redsync {
once.Do(func() {
conn = connect()
})
return conn
}
rs = &Connection{
inner: initInner,
}
}
//MutexManager Mutex manager over Redis
type MutexManager interface {
Lock(name string) (*redsync.Mutex, error)
}
//ClientImpl Real Redis mutex client
type ClientImpl struct{}
//Lock Creates locked mutex
func (r ClientImpl) Lock(name string) (*redsync.Mutex, error) {
logger := logging.FromContext(ctx).Named("efgs.redis-mutex.Lock")
mutex := rs.inner().NewMutex(name, redsync.WithExpiry(time.Hour)) // expiration of 1 hour is just to be sure
logger.Debugf("Trying to acquire '%v' exclusive lock", name)
err := mutex.Lock()
if err != nil {
return nil, err
}
return mutex, nil
}