Go之路(三十一):etcd的学习
etcd的学习
etcd测试链接
package main
import (
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
/*
DialTimeout time.Duration `json:"dial-timeout"`
Endpoints []string `json:"endpoints"`
*/
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
}
输出如下:
PS E:\golang\go_pro\src\safly> go run main.go
connect succ
PS E:\golang\go_pro\src\safly>
etcd存取值
package main
import (
"context"
"fmt"
"github.com/coreos/etcd/clientv3"
"time"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
//设置1秒超时,访问etcd有超时控制
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
//操作etcd
_, err = cli.Put(ctx, "/logagent/conf/", "sample_value")
//操作完毕,取消etcd
cancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
}
//取值,设置超时为1秒
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", string(ev.Key), string(ev.Value))
}
}
输出如下:
PS E:\golang\go_pro\src\safly> go run example.go
connect succ
/logagent/conf/ : sample_value
etcd检测Watch
package main
import (
"fmt"
"context"
etcd_client "go.etcd.io/etcd/clientv3"
"time"
)
func main(){
cli ,err := etcd_client.New(etcd_client.Config{
Endpoints : []string{"localhost:2379"},
DialTimeout : 5* time.Second,
})
if err != nil {
fmt.Printf("err:%v",err)
}
defer cli.Close()
ctx , cancle := context.WithTimeout(context.Background(), time.Second)
cli.Put(ctx, "userid", "123123")
cancle()
resp := cli.Watch(context.Background(), "userid")
for res := range resp{
for _, wres := range res.Events{
fmt.Println(string(wres.Kv.Key),string(wres.Kv.Value))
}
fmt.Println("111")
}
}
Wach函数原理图

Cliemt 通过watch函数建立长连接,不用放在死循环内,如果etcd那边有变化,可以直接被返回值捕获到。

如果加入for循环,则不打印111,说明最外层循环没用
另外,需要用string进行转换

浙公网安备 33010602011771号