-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo7.go
More file actions
87 lines (71 loc) · 1.79 KB
/
Copy pathdemo7.go
File metadata and controls
87 lines (71 loc) · 1.79 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
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
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"github.com/coreos/etcd/mvcc/mvccpb"
"time"
)
/**
* @Author: super
* @Date: 2021-02-01 21:58
* @Description:
**/
func main() {
var (
config clientv3.Config
client *clientv3.Client
err error
kv clientv3.KV
watcher clientv3.Watcher
getResp *clientv3.GetResponse
watchStartRevision int64
watchRespChan <-chan clientv3.WatchResponse
watchResp clientv3.WatchResponse
event *clientv3.Event
)
// 客户端配置
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
}
kv = clientv3.NewKV(client)
go func() {
for{
kv.Put(context.TODO(), "/cron/jobs/job7", "job7")
kv.Delete(context.TODO(), "/cron/jobs/job7")
time.Sleep(2 * time.Second)
}
}()
if getResp, err = kv.Get(context.TODO(), "/cron/jobs/job7"); err != nil{
fmt.Println(err)
return
}
if len(getResp.Kvs) != 0{
fmt.Println("当前值:", string(getResp.Kvs[0].Value))
}
watchStartRevision = getResp.Header.Revision + 1
watcher = clientv3.NewWatcher(client)
fmt.Println("从该版本向后监听:", watchStartRevision)
ctx, cancelFunc := context.WithCancel(context.TODO())
time.AfterFunc(5 * time.Second, func() {
cancelFunc()
})
watchRespChan = watcher.Watch(ctx, "/cron/jobs/job7", clientv3.WithRev(watchStartRevision))
// 处理kv变化事件
for watchResp = range watchRespChan {
for _, event = range watchResp.Events {
switch event.Type {
case mvccpb.PUT:
fmt.Println("修改为:", string(event.Kv.Value), "Revision:", event.Kv.CreateRevision, event.Kv.ModRevision)
case mvccpb.DELETE:
fmt.Println("删除了", "Revision:", event.Kv.ModRevision)
}
}
}
}