forked from bsm/redis-lock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
55 lines (46 loc) · 1.02 KB
/
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
51
52
53
54
55
package lock_test
import (
"fmt"
"time"
"github.com/bsm/redis-lock"
"github.com/go-redis/redis"
)
func Example() {
// Connect to Redis
client := redis.NewClient(&redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
})
defer client.Close()
// Create a new locker with default settings
locker := lock.New(client, "lock.foo", nil)
// Try to obtain lock
hasLock, err := locker.Lock()
if err != nil {
panic(err.Error())
} else if !hasLock {
fmt.Println("could not obtain lock!")
return
}
// Don't forget to defer Unlock!
defer locker.Unlock()
fmt.Println("I have a lock!")
// Sleep and check if still locked afterwards.
time.Sleep(200 * time.Millisecond)
if locker.IsLocked() {
fmt.Println("My lock has expired!")
}
// Renew your lock
renewed, err := locker.Lock()
if err != nil {
panic(err.Error())
} else if !renewed {
fmt.Println("could not renew lock!")
return
}
fmt.Println("I have renewed my lock!")
// Output:
// I have a lock!
// My lock has expired!
// I have renewed my lock!
}