当前位置:网站首页>【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 -------------------
边栏推荐
- What are the requirements for new bonds? Is it safe to play new bonds
- 35岁危机?内卷成程序员代名词了…
- The "open source star picking program" container pulls private images from harbor, which is a necessary skill for cloud native advanced technology
- Development notes of wedding studio applet based on wechat applet
- Approximate fair queuing on programmable switches reading notes
- How to write a great online user manual in 7 steps
- Design of hardware switch with programmable full function rate limiter
- 直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践
- How to avoid the "black swan" incident in the gene field: a security war behind a preventive "recall"
- What conditions do you need to meet to fight new debts? Is it safe to fight new debts
猜你喜欢

直播回顾 | 云原生混部系统 Koordinator 架构详解(附完整PPT)

Kubernetes 资源拓扑感知调度优化

Rendering of kotlin jetpack compose tab using animatedvisibility

Convex optimization notes

直播分享| 腾讯云 MongoDB 智能诊断及性能优化实践

Robust extraction of specific signals with time structure (Part 2)

20 provinces and cities announce the road map of the meta universe

Open source SPL redefines OLAP server

Ready to migrate to the cloud? Please accept this list of migration steps

GL Studio 5 installation and experience
随机推荐
Rendering of kotlin jetpack compose tab using animatedvisibility
官宣.NET 7 预览版5
[cloud trends] the four highlights of Huawei cloud store brand new release are here
After the collapse of UST, will the stable currency market pattern usher in new opportunities?
LeetCode 473. Match to square
为什么你的数据图谱分析图上只显示一个值?
String Day6 of Li Kou daily practice
Are there conditions for making new bonds? Is it safe to make new bonds
What are the useful personnel management software? Personnel management system software ranking!
游戏资产复用:更快找到所需游戏资产的新方法
如何避免基因领域“黑天鹅”事件:一场预防性“召回”背后的安全保卫战
GL Studio 5 安装与体验
JDBC 在性能测试中的应用
区块哈希竞猜游戏系统开发(dapp)
活动报名 | MongoDB 5.0 时序存储特性介绍
Gaussdb (DWS) database intelligent monitoring operation and maintenance service - node monitoring indicators
Application of MySQL time function, simple problem
FlagAI飞智:AI基础模型开源项目,支持一键调用OPT等模型
The golden nine silver ten, depends on this detail, the offer obtains the soft hand!
Design of hardware switch with programmable full function rate limiter