Skip to content

Commit a448f21

Browse files
committed
<添加><consul><分布式锁>
1 parent b66663f commit a448f21

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

demo/consul/lock/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Consul 分布式锁
2+
==============
3+

demo/consul/lock/main.go

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
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+
}

0 commit comments

Comments
 (0)