-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
77 lines (67 loc) · 1.36 KB
/
main.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
package main
import (
"context"
"fmt"
"sync"
"time"
"github.com/da440dil/go-locker"
"github.com/go-redis/redis/v8"
)
func main() {
client := redis.NewClient(&redis.Options{})
defer client.Close()
// Create locker.
lkr := locker.NewLocker(client)
ctx := context.Background()
key := "key"
err := client.Del(ctx, key).Err()
requireNoError(err)
lock := func() {
// Try to apply lock.
lr, err := lkr.Lock(ctx, key, time.Second)
requireNoError(err)
if !lr.OK() {
fmt.Printf("Failed to apply lock, retry after %v\n", lr.TTL())
return
}
fmt.Println("Lock applied")
// Try to release lock.
defer func() {
ok, err := lr.Unlock(ctx)
requireNoError(err)
if ok {
fmt.Println("Lock released")
} else {
fmt.Println("Failed to release lock")
}
}()
time.Sleep(time.Millisecond * 100) // some code here
// Optionally try to extend lock.
r, err := lr.Lock.Lock(ctx, time.Second)
requireNoError(err)
if !r.OK() {
fmt.Printf("Failed to extend lock, retry after %v\n", lr.TTL())
return
}
fmt.Println("Lock extended")
}
var wg sync.WaitGroup
wg.Add(2)
for i := 0; i < 2; i++ {
go func() {
defer wg.Done()
lock()
}()
}
wg.Wait()
// Output:
// Lock applied
// Failed to apply lock, retry after 999ms
// Lock extended
// Lock released
}
func requireNoError(err error) {
if err != nil {
panic(err)
}
}