-
Notifications
You must be signed in to change notification settings - Fork 0
/
demo10.go
96 lines (86 loc) · 1.92 KB
/
demo10.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
/**
* @Author: super
* @Date: 2021-02-07 19:04
* @Description:
**/
func main() {
var(
config clientv3.Config
client *clientv3.Client
err error
lease clientv3.Lease
leaseGrantResp *clientv3.LeaseGrantResponse
leaseId clientv3.LeaseID
putResp *clientv3.PutResponse
getResp *clientv3.GetResponse
keepResp *clientv3.LeaseKeepAliveResponse
keepRespChan <-chan *clientv3.LeaseKeepAliveResponse
kv clientv3.KV
)
config = clientv3.Config{
Endpoints:[]string{"127.0.0.1:2379"},
DialTimeout:5 * time.Second,
}
//创建客户端
if client, err = clientv3.New(config); err != nil{
fmt.Println(err)
return
}
lease = clientv3.NewLease(client)
// 申请续约
if leaseGrantResp, err = lease.Grant(context.TODO(), 5); err != nil{
fmt.Println(err)
return
}
leaseId = leaseGrantResp.ID
fmt.Println("id", leaseId)
if leaseGrantResp, err = lease.Grant(context.TODO(), 5); err != nil{
fmt.Println(err)
return
}
leaseId1 := leaseGrantResp.ID
fmt.Println("id1", leaseId1)
if keepRespChan, err = lease.KeepAlive(context.TODO(), leaseId); err != nil{
fmt.Println(err)
return
}
go func() {
for {
select {
case keepResp = <- keepRespChan:
if keepResp == nil{
fmt.Println("租约失效")
return
}else{
fmt.Println("收到自动续租应答:", keepResp.ID)
}
}
}
}()
kv = clientv3.NewKV(client)
if putResp, err = kv.Put(context.TODO(), "/cron/lock/job1", "", clientv3.WithLease(leaseId)); err != nil{
fmt.Println(err)
return
}
fmt.Println("写入成功:", putResp.Header.Revision)
// 定时的看一下key过期了没有
for {
if getResp, err = kv.Get(context.TODO(), "/cron/lock/job1"); err != nil {
fmt.Println(err)
return
}
if getResp.Count == 0 {
fmt.Println("kv过期了")
break
}
fmt.Println("还没过期:", getResp.Kvs)
time.Sleep(2 * time.Second)
}
}