etcdetcd
1.安装
go get go.etcd.io/etcd/client/v3
2.put与get操作
putget
在代码操作之前,先确保服务器etcd是否已经启动
#查看进程
ps -ef | grep etcd
#如果没有启动,就先启动吧
#不挂断启动
cd /home/randyfield/etcd-release/etcd-v3.2.32-linux-amd64/
nohup ./etcd &
#命令行设置值
export ETCDCTL_API=3
./etcdctl put name "Garfield"
2.1 get值
keyname
package main
import (
"context"
"fmt"
"time"
clientv3 "go.etcd.io/etcd/client/v3"
)
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"192.168.31.204:2379"}, //如果是集群,就在后面加所有的节点[]string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
// handle error!
fmt.Printf("connect to etcd failed, err:%v\n", err)
return
}
defer cli.Close()
//context超时控制
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
resp, err := cli.Get(ctx, "name")
cancel()
if err != nil {
fmt.Printf("get from etcd failed,err %v\n", err)
}
//遍历键值对
for _, kv := range resp.Kvs {
fmt.Printf("%s:%s \n", kv.Key, kv.Value)
}
}
go build -o etcd-config-center.exe
.\etcd-config-center.exe
小插曲:遇到问题
报错
连接超时了
{"level":"warn","ts":"2021-05-04T14:45:41.425+0800","caller":"v3@v3.5.0-alpha.0/retry_interceptor.go:62","msg":"retrying of unary invoker failed","target":"etcd-endpoints://0xc0000b2380/#initially=[192.168.31.204:2379]","attempt":0,"error":"rpc error: code = DeadlineExceeded desc = context deadline exceeded"}
get from etcd failed,err context deadline exceeded
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xc0000005 code=0x0 addr=0x10 pc=0x9a5781]
goroutine 1 [running]:
main.main()
问题推测
根据错误,盲猜一手端口监听问题
找到原因
etcd
lsof -i:2379
lsof -i:3000
解决问题
localhostnohup
ps -ef | grep etcd
kill -9 1409
etcd
nohup ./etcd --listen-client-urls http://0.0.0.0:2379 --advertise-client-urls http://0.0.0.0:2379 --listen-peer-urls http://0.0.0.0:2380 &
2.2 put值
go build -o etcd-config-center.exe
.\etcd-config-center.exe
putkey-value
//omit above code...
//continue..
//put值
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
_, err = cli.Put(ctx, "address", "成都市高新区")
cancel()
if err != nil {
fmt.Printf("put to etcd failed, err:%v\n", err)
return
}
用etcdctl验证一下吧
./etcdctl get address
ETCDCTL_API=3
export ETCDCTL_API=3
putset
3.watch操作
watch
为了演示效果,继续在上面的代码增加:
// watch key:address change 监控etcd中key的变化-创建、更改、删除
rch := cli.Watch(context.Background(), "address") // <-chan WatchResponse
for wresp := range rch {
for _, ev := range wresp.Events {
fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}
运行
go build -o etcd-config-center.exe
.\etcd-config-center.exe
服务器终端执行
./etcdctl put address "成都市高新区应龙南一路"
./etcdctl del address
./etcdctl put address "四川省巴中市"
etcd
------------------- End -------------------