forked from bsm/redislock
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
56 lines (46 loc) · 1.21 KB
/
example_test.go
File metadata and controls
56 lines (46 loc) · 1.21 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
package redislock_test
import (
"fmt"
"log"
"time"
"github.com/redis/go-redis/v9"
"github.com/verloop/redislock"
)
func Example() {
// Connect to redis.
client := redis.NewClient(&redis.Options{MaxIdleConns: 3, ConnMaxIdleTime: 240 * time.Hour, DB: 1})
// Create a new lock client.
locker := redislock.New(client)
// Try to obtain lock.
lock, err := locker.Obtain("my-key", 100*time.Millisecond, nil)
if err == redislock.ErrNotObtained {
fmt.Println("Could not obtain lock!")
} else if err != nil {
log.Fatalln(err)
}
// Don't forget to defer Release.
defer lock.Release()
fmt.Println("I have a lock!")
// Sleep and check the remaining TTL.
time.Sleep(50 * time.Millisecond)
if ttl, err := lock.TTL(); err != nil {
log.Fatalln(err)
} else if ttl > 0 {
fmt.Println("Yay, I still have my lock!")
}
// Extend my lock.
if err := lock.Refresh(100*time.Millisecond, nil); err != nil {
log.Fatalln(err)
}
// Sleep a little longer, then check.
time.Sleep(100 * time.Millisecond)
if ttl, err := lock.TTL(); err != nil {
log.Fatalln(err)
} else if ttl == 0 {
fmt.Println("Now, my lock has expired!")
}
// Output:
// I have a lock!
// Yay, I still have my lock!
// Now, my lock has expired!
}