当前位置:网站首页>[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 -------------------

原网站

版权声明
本文为[DDGarfield]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231941490780.html