【etcd】etcd使用与集群搭建博文中已经大致介绍了 etcd与集群搭建,下面将针对etcd的使用场景之一的 配置中心做开发实战。

1.安装

go get go.etcd.io/etcd/client/v3

2.put与get操作

put命令用来设置key-value键值对数据,get命令用来根据key获取值。

在代码操作之前,先确保服务器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()
问题推测

根据错误,盲猜一手端口监听问题

image-20210504145514330

找到原因

比较一下一个正常外网可以访问的端口与etcd端口

lsof -i:2379
lsof -i:3000

image-20210504150448522

解决问题

两相对比,基本可以确认是因为只监听了localhost,先由于是通过nohup启动的,所以先杀掉进程吧:

ps -ef | grep etcd
kill -9 1409

image-20210504150702791

然后再通过指定参数进行启动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 &

image-20210504151232100

2.2 put值

go build -o etcd-config-center.exe
.\etcd-config-center.exe

image-20210504152215146

再用代码put一个新的key-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

image-20210504153220648

注意:服务端必须设置了环境变量ETCDCTL_API=3

export ETCDCTL_API=3

否则,put不会成功,因为老版本是用set

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 "四川省巴中市"

image-20210504153220648

就先到这儿吧,之后会补充etcd的服务注册、服务发现、分布式锁的用法。