当前位置:网站首页>[golang] use go language to operate etcd - configuration center
[golang] use go language to operate etcd - configuration center
2022-06-23 20:05:00 【DDGarfield】
【etcd】etcd Use and cluster setup The blog has outlined etcd Build with the cluster , The following will focus on etcd One of the usage scenarios of Configuration center Do development practice .
1. install
go get go.etcd.io/etcd/client/v3
2.put And get operation
put The command is used to set key-value Key value pair data ,get The command is used according to key Get value .
Before the code operates , Make sure the server etcd Has it been started?
# Check the process
ps -ef | grep etcd
# If not started , Just start
# Start without hanging up
cd /home/randyfield/etcd-release/etcd-v3.2.32-linux-amd64/
nohup ./etcd &
# Command line setting values
export ETCDCTL_API=3
./etcdctl put name "Garfield"
2.1 get value
Above, we have set it with the command line key by name Value , Let's use the code to get :
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"}, // If it's a cluster , Just add all the nodes behind []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 Timeout control
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)
}
// Traversal key value pairs
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
episode : Have a problem
Report errors
The connection timed out
{"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()
The problem is conjecture
According to the mistake , Blind guessing the first-hand port listening problem
Find the cause
Compare a port that can be accessed by a normal external network with etcd port
lsof -i:2379
lsof -i:3000
solve the problem
Two phase comparison , Basically, it can be confirmed that it only monitors localhost, First, through nohup Starting up , So kill the process first :
ps -ef | grep etcd
kill -9 1409
Then start by specifying parameters 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 value
go build -o etcd-config-center.exe
.\etcd-config-center.exe
Then use the code put A new key-value
//omit above code...
//continue..
//put value
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
_, err = cli.Put(ctx, "address", " Chengdu hi tech Zone ")
cancel()
if err != nil {
fmt.Printf("put to etcd failed, err:%v\n", err)
return
}
use etcdctl Check it out
./etcdctl get address
Be careful : The server must set the environment variable ETCDCTL_API=3
export ETCDCTL_API=3
otherwise ,put It won't work , Because the old version used set
3.watch operation
Use watch To get notification of future changes . Implement configuration hot loading
For demonstration , Continue to add... In the above code :
// watch key:address change monitor etcd in key The change of - establish 、 change 、 Delete
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)
}
}
function
go build -o etcd-config-center.exe
.\etcd-config-center.exe
The server terminal executes
./etcdctl put address " Yinglong South 1st Road, Chengdu hi tech Zone "
./etcdctl del address
./etcdctl put address " Bazhong City, Sichuan Province "
Come here first , I'll add later etcd Service registration for 、 Service discovery 、 Usage of distributed locks .
------------------- End -------------------
边栏推荐
- LeetCode 260. Number III that appears only once
- Can the biggest gamefi crash victim survive the bear market in May| May Monthly Report
- Hardware development notes (6): basic process of hardware development, making a USB to RS232 module (5): creating USB package library and associating principle graphic devices
- SQL联合查询(内联、左联、右联、全联)的语法
- Rendering of kotlin jetpack compose tab using animatedvisibility
- 宝安区航城街道领导一行莅临联诚发参观调研
- Tupu software digital twin intelligent water service, breaking through the development dilemma of sponge City
- Kinsoku jikou desu新浪股票接口变动
- Interpreting the 2022 agile coaching industry status report
- Kotlin jetpack compose Tab的渲染 AnimatedVisibility的使用
猜你喜欢

LeetCode 260. 只出现一次的数字 III

The "open source star picking program" container pulls private images from harbor, which is a necessary skill for cloud native advanced technology

盘点四种WiFi加密标准:WEP、WPA、WPA2、WPA3

基于 ShardingSphere 的得物数据库中间件平台“彩虹桥”演进之路

JDBC 在性能测试中的应用

测试的重要性及目的

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

Hotline salon issue 26 - cloud security session

Implementation of microblog system based on SSM

开源 SPL 重新定义 OLAP Server
随机推荐
游戏资产复用:更快找到所需游戏资产的新方法
「开源摘星计划」Containerd拉取Harbor中的私有镜像,云原生进阶必备技能
How to write a great online user manual in 7 steps
SAP实施项目上的内部顾问与外部顾问,相互为难还是相互成就?
金九银十,靠这个细节,offer拿到手软!
打新债好不好 打新债安全吗
打新债 要求 打新债安全吗
Tcp/udp Fundamentals
logstash启动 -r 参数
Goldfish rhca memoirs: do447 managing user and team access -- effectively managing users with teams
QGIS import WMS or WMTs
Live broadcast review | detailed explanation of koordinator architecture of cloud native hybrid system (complete ppt attached)
【Golang】快速复习指南QuickReview(二)——切片slice
国内期货开户怎么开?哪家期货公司开户更安全?
LeetCode 260. Number III that appears only once
What conditions do you need to meet to fight new debts? Is it safe to fight new debts
国元期货交易软件正规吗?如何安全下载?
基于SSM实现微博系统
宝安区航城街道领导一行莅临联诚发参观调研
Daily question brushing record (II)