当前位置:网站首页>【Golang】使用Go语言操作etcd——配置中心
【Golang】使用Go语言操作etcd——配置中心
2022-06-23 19:42:00 【DDGarfield】
【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值
上面我们已经用命令行设置了key为name的值,下面就用代码获取一下:
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":"[email protected]/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
解决问题
两相对比,基本可以确认是因为只监听了localhost,先由于是通过nohup启动的,所以先杀掉进程吧:
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
再用代码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
注意:服务端必须设置了环境变量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 "四川省巴中市"
就先到这儿吧,之后会补充etcd的服务注册、服务发现、分布式锁的用法。
------------------- End -------------------
边栏推荐
- Kinsoku jikou desu新浪股票接口变动
- 35歲危機?內卷成程序員代名詞了…
- JS高级程序设计第 4 版:生成器的学习
- 不止雷军 iQOO产品经理也称赞高通骁龙8+:焕然一新
- 火线沙龙第26期-多云安全专场
- Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage
- 打新债需要具备什么条件 打新债安全吗
- LeetCode 473. Match to square
- Hotline salon issue 26 - cloud security session
- Syntaxe des requêtes fédérées SQL (inline, left, right, full)
猜你喜欢

如何避免基因领域“黑天鹅”事件:一场预防性“召回”背后的安全保卫战

Helix QAC is updated to 2022.1 and will continue to provide high standard compliance coverage

Eight misunderstandings, broken one by one (final): the cloud is difficult to expand, the customization is poor, and the administrator will lose control?

JS高级程序设计第 4 版:生成器的学习

Hotline salon issue 26 - cloud security session

IDEA控制台显示中文乱码

如何使用物联网低代码平台进行流程管理?

测试的重要性及目的

20省市公布元宇宙路线图

基于 ShardingSphere 的得物数据库中间件平台“彩虹桥”演进之路
随机推荐
OHOS LTS 3.0移植到RaspberryPi 4B
官宣.NET 7 预览版5
Are there conditions for making new bonds? Is it safe to make new bonds
宝安区航城街道领导一行莅临联诚发参观调研
不止雷军 iQOO产品经理也称赞高通骁龙8+:焕然一新
Rstudio 1.4 software installation package and installation tutorial
八大误区,逐个击破(终篇):云难以扩展、定制性差,还会让管理员失去控制权?
测试的重要性及目的
@@脚本实现Ishell自动部署
Uniswap founder: no independent token will be issued for genie, and Genie products will be integrated into the uniswap interface
Activity registration | introduction to mongodb 5.0 sequential storage features
墨天轮访谈 | IvorySQL王志斌—IvorySQL,一个基于PostgreSQL的兼容Oracle的开源数据库
Elastricearch's fragmentation principle of the second bullet
重庆 奉节耀奎塔,建成后当地连中五名进士,是川江航运的安全塔
I came from a major, so I didn't want to outsource
Official announcement. Net 7 preview 5
Programmable data plane (paper reading)
Ugeek's theory 𞓜 application and design of observable hyperfusion storage system
FlagAI飞智:AI基础模型开源项目,支持一键调用OPT等模型
直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践