Redis

Distributed Lock

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
type RedisLock struct {
client *redis.Client
timeout int64
}

func NewRedisLock(client *redis.Client, config *base.Config) dependency.Locker {
return &RedisLock{client: client, timeout: config.RedisLockTimeoutSecond}
}

func (r *RedisLock) Lock(ctx context.Context, key string) (unlockFunc func() error, success bool) {
id := uuid.New().String()
result := r.client.SetNX(ctx, key, id, time.Duration(r.timeout)*time.Second)
if success, err := result.Result(); err != nil || !success {
return func() error { return nil }, false
}
return func() error {
result, err := r.client.Get(ctx, key).Result()
if err != nil {
return err
}
if result == id {
return r.client.Del(ctx, key).Err()
}
return errors.New("key not fount")
}, true
}