forked from segmentio/redlock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
50 lines (42 loc) · 933 Bytes
/
example_test.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
package redlock
import (
"fmt"
"time"
"github.com/bsm/redis-lock"
"gopkg.in/redis.v5"
)
func Example() {
// Connect to Redis
client := redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
})
defer client.Close()
// Obtain a new lock with default settings
lock, err := lock.ObtainLock(client, "lock.foo", nil)
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return
} else if lock == nil {
fmt.Println("ERROR: could not obtain lock")
return
}
// Don't forget to unlock in the end
defer lock.Unlock()
// Run something
fmt.Println("I have a lock!")
time.Sleep(200 * time.Millisecond)
// Renew your lock
ok, err := lock.Lock()
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return
} else if !ok {
fmt.Println("ERROR: could not renew lock")
return
}
fmt.Println("I have renewed my lock!")
// Output:
// I have a lock!
// I have renewed my lock!
}