MCPcopy
hub / github.com/bsm/redislock / Example

Function Example

example_test.go:13–65  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

11)
12
13func Example() {
14 // Connect to redis.
15 client := redis.NewClient(&redis.Options{
16 Network: "tcp",
17 Addr: "127.0.0.1:6379",
18 })
19 defer client.Close()
20
21 // Create a new lock client.
22 locker := redislock.New(client)
23
24 ctx := context.Background()
25
26 // Try to obtain lock.
27 lock, err := locker.Obtain(ctx, "my-key", 100*time.Millisecond, nil)
28 if err == redislock.ErrNotObtained {
29 fmt.Println("Could not obtain lock!")
30 return
31 } else if err != nil {
32 log.Fatalln(err)
33 return
34 }
35
36 // Don't forget to defer Release.
37 defer lock.Release(ctx)
38 fmt.Println("I have a lock!")
39
40 // Sleep and check the remaining TTL.
41 time.Sleep(50 * time.Millisecond)
42 if ttl, err := lock.TTL(ctx); err != nil {
43 log.Fatalln(err)
44 } else if ttl > 0 {
45 fmt.Println("Yay, I still have my lock!")
46 }
47
48 // Extend my lock.
49 if err := lock.Refresh(ctx, 100*time.Millisecond, nil); err != nil {
50 log.Fatalln(err)
51 }
52
53 // Sleep a little longer, then check.
54 time.Sleep(100 * time.Millisecond)
55 if ttl, err := lock.TTL(ctx); err != nil {
56 log.Fatalln(err)
57 } else if ttl == 0 {
58 fmt.Println("Now, my lock has expired!")
59 }
60
61 // Output:
62 // I have a lock!
63 // Yay, I still have my lock!
64 // Now, my lock has expired!
65}
66
67func ExampleClient_Obtain_retry() {
68 client := redis.NewClient(&redis.Options{Network: "tcp", Addr: "127.0.0.1:6379"})

Callers

nothing calls this directly

Calls 5

NewFunction · 0.92
ObtainMethod · 0.80
ReleaseMethod · 0.80
TTLMethod · 0.80
RefreshMethod · 0.80

Tested by

no test coverage detected