File tree Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Expand file tree Collapse file tree 2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change
1
+ Consul 分布式锁
2
+ ==============
3
+
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ import (
4
+ "context"
5
+ "log"
6
+ "net/http"
7
+
8
+ "github.com/hashicorp/consul/api"
9
+ )
10
+
11
+ func main () {
12
+ client , err := api .NewClient (& api.Config {Address : "192.168.1.8:8500" })
13
+ if err != nil {
14
+ log .Fatal (err .Error ())
15
+ }
16
+
17
+ opts := & api.LockOptions {
18
+ Key : "webhook_receiver/1" ,
19
+ Value : []byte ("set by sender 1" ),
20
+ SessionTTL : "10s" ,
21
+ SessionOpts : & api.SessionEntry {
22
+ Checks : []string {"serfHealth" },
23
+ Behavior : "release" ,
24
+ },
25
+ }
26
+
27
+ lock , err := client .LockOpts (opts )
28
+ stopCh := make (chan struct {})
29
+
30
+ lockCh , err := lock .Lock (stopCh )
31
+
32
+ if err != nil {
33
+ panic (err )
34
+ }
35
+
36
+ cancelCtx , cancelRequest := context .WithCancel (context .Background ())
37
+ req , _ := http .NewRequest ("GET" , "https://www.baidu.com" , nil )
38
+ req = req .WithContext (cancelCtx )
39
+ go func () {
40
+ http .DefaultClient .Do (req )
41
+ select {
42
+ case <- cancelCtx .Done ():
43
+ log .Println ("request cancelled" )
44
+ default :
45
+ log .Println ("request done" )
46
+
47
+ err = lock .Unlock ()
48
+ if err != nil {
49
+ log .Println ("lock already unlocked" )
50
+ }
51
+ }
52
+ }()
53
+ go func () {
54
+ <- lockCh
55
+ cancelRequest ()
56
+ }()
57
+
58
+ }
You can’t perform that action at this time.
0 commit comments