-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock.go
More file actions
70 lines (56 loc) · 1.57 KB
/
lock.go
File metadata and controls
70 lines (56 loc) · 1.57 KB
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
package dlock
import (
"context"
"errors"
"math/rand"
"time"
"github.com/go-redis/redis/v8"
)
var (
lockScript = redis.NewScript(`return redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2])`)
unlockScript = redis.NewScript(`if redis.call("GET", KEYS[1]) == ARGV[1] then return redis.call("DEL", KEYS[1]) else return 0 end`)
)
type Lock struct {
c *redis.Client
}
// New creates Lock object
func New(addr string) *Lock {
client := redis.NewClient(&redis.Options{Addr: addr, Password: "", DB: 0})
return &Lock{c: client}
}
// Lock attempts to put a lock on the key for a specified duration.
// returns error if failed.
func (l *Lock) Lock(key string, timeout time.Duration) (string, error) {
id := randStr(10)
res, err := lockScript.Run(context.Background(), l.c, []string{"dlock:" + key}, id, timeout.Milliseconds()).Text()
if err != nil && err != redis.Nil {
return "", err
}
if res != "OK" {
return "", errors.New("Lock failed")
}
return id, nil
}
// Unlock attempts to remove the lock on a key if the id matches.
// returns error if failed.
func (l *Lock) Unlock(key, id string) error {
res, err := unlockScript.Run(context.Background(), l.c, []string{"dlock:" + key}, id).Int()
if err != redis.Nil && err != nil {
return err
}
if res != 1 {
return errors.New("Unlock failed")
}
return nil
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
func randStr(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func init() {
rand.Seed(time.Now().UnixNano())
}