监控代码

package main

import (
"go.etcd.io/etcd/clientv3"
"time"
"fmt"
"context"
) func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints:[]string{"localhost:2379", "localhost:23279", "localhost:33279"},//etcd集群三个实例的端口
DialTimeout:*time.Second,
}) if err != nil {
fmt.Println("connect failed, err:", err)
return
} fmt.Println("connect succ") defer cli.Close() for true {
rch := cli.Watch(context.Background(), "/logagent/conf/")//阻塞在这里,如果没有key里没有变化,就一直停留在这里
for wresp := range rch{
for _, ev := range wresp.Events{
fmt.Printf("%s %q:%q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}
}
}

配置变更代码

package main

import (
"go.etcd.io/etcd/clientv3"
"time"
"fmt"
"context"
) func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints:[]string{"localhost:2379", "localhost:23279", "localhost:33279"}, //etcd的集群的三个实例端口
DialTimeout: *time.Second,
}) if err != nil {
fmt.Println("connect failed, err:", err)
return
} fmt.Println("connect succ")
defer cli.Close() ctx, cancel := context.WithTimeout(context.Background(), *time.Second)
_, err = cli.Put(ctx, "/logagent/conf/", "samplevalue")
cancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
} ctx, cancel = context.WithTimeout(context.Background(), time.Second)
resp, err := cli.Get(ctx, "/logagent/conf/")
cancel()
if err != nil {
fmt.Println("get failed, err:", err)
return
}
for _, ev := range resp.Kvs{
fmt.Printf("%s:%s\n", ev.Key, ev.Value)
}
}

执行后, 监控代码的执行结果为
[GO] go使用etcd和watch方法进行实时的配置变更-LMLPHP

05-11 02:22