当前位置:网站首页>【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 -------------------
边栏推荐
- 好用的人事管理软件有哪些?人事管理系统软件排名!
- Leetcode daily question - 30 Concatenate substrings of all words
- RStudio 1.4软件安装包和安装教程
- GL Studio 5 installation and experience
- Flagai Feizhi: AI basic model open source project, which supports one click call of OPT and other models
- Shell Scripting
- Deeply understand and grasp the basic characteristics of digital economy
- 基于微信小程序的婚纱影楼小程序开发笔记
- Uniswap创始人:不会为Genie发行独立代币,Genie产品将集成至Uniswap界面
- [cloud trends] the four highlights of Huawei cloud store brand new release are here
猜你喜欢

Activity registration | introduction to mongodb 5.0 sequential storage features

「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能

I came from a major, so I didn't want to outsource

LeetCode 260. Number III that appears only once

小程序开发框架推荐

准备好迁移上云了?请收下这份迁移步骤清单

不止雷军 iQOO产品经理也称赞高通骁龙8+:焕然一新

Real topic of the 13th National Competition of single chip microcomputer in the Blue Bridge Cup

Interpreting the 2022 agile coaching industry status report

Leetcode daily question - 30 Concatenate substrings of all words
随机推荐
Implementation of microblog system based on SSM
How to install SSL certificates in Microsoft Exchange 2010
Flagai Feizhi: AI basic model open source project, which supports one click call of OPT and other models
I came from a major, so I didn't want to outsource
Matrix analysis notes (I)
Leetcode daily question - 30 Concatenate substrings of all words
Why is only one value displayed on your data graph?
Importance and purpose of test
JDBC 在性能測試中的應用
Matrix analysis notes (II)
Stochastic process -- Markov chain
Application of JDBC in performance test
vs2022scanf函数的使用,使用scanf的报错-返回值被忽略:解决·方法
Shell Scripting
FlagAI飞智:AI基础模型开源项目,支持一键调用OPT等模型
Rendering of kotlin jetpack compose tab using animatedvisibility
教你如何用网页开发桌面应用
OHOS LTS 3.0移植到RaspberryPi 4B
不止雷军 iQOO产品经理也称赞高通骁龙8+:焕然一新
活动报名 | MongoDB 5.0 时序存储特性介绍