安装部署
docker pull bitnami/etcd
docker run -d --name etcd-server \
--network mynet2 \
--publish 2379:2379 \
--publish 2380:2380 \
--env ALLOW_NONE_AUTHENTICATION=yes \
--env ETCD_ADVERTISE_CLIENT_URLS=http://0.0.0.0:2379 \
bitnami/etcd:latest
go get go.etcd.io/etcd/client/v3
put和get,以及watch操作
package main
import (
"context"
"fmt"
"go.etcd.io/etcd/client/v3"
"net"
"strings"
"time"
)
var cli *clientv3.Client
func main() {
var err error
cli, err = clientv3.New(clientv3.Config{
Endpoints: []string{"114.116.21.20:2379"},
DialTimeout: time.Second * 5,
})
if err != nil {
fmt.Printf("connect to etcd failed,err:%v\n", err)
}
defer cli.Close()
ip := GetMachineIp()
key1 := "tailFileConfig" + "_" + ip
value1 :=
`{
"collects":[
{
"path":"D:\\GoProject\\src\\GoTest\\kafka\\logagent\\conf\\testLog\\a.log",
"topic":"a_topic"
},
{
"path":"D:\\GoProject\\src\\GoTest\\kafka\\logagent\\conf\\testLog\\b.log",
"topic":"b_topic"
},
{
"path":"D:\\GoProject\\src\\GoTest\\kafka\\logagent\\conf\\testLog\\c.log",
"topic":"c_topic"
}
]
}`
Put(key1, value1)
key2 := "kafkaConfig"
value2 := "{\"address\":[\"114.116.21.20:9092\"],\"msgChanSize\":100000}"
Put(key2, value2)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
gr, err := cli.Get(ctx, key1)
if err != nil {
fmt.Printf("get etcd failed,err:%v", err)
return
}
for _, kv := range gr.Kvs {
fmt.Printf("key:%s,value:%s", kv.Key, kv.Value)
}
cancel()
go func() {
watchCh := cli.Watch(context.Background(), key1)
for wresp := range watchCh {
for _, event := range wresp.Events {
fmt.Printf("type:%s,key:%s,value:%s\n", event.Type, event.Kv.Key, event.Kv.Value)
}
}
}()
}
func Put(key, value string) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
_, err := cli.Put(ctx, key, value)
if err != nil {
fmt.Printf("put to etcd failed,err:%v\n", err)
cancel()
return
}
cancel()
}
func GetMachineIp() string {
conn, err := net.Dial("udp", "baidu.com:80")
if err != nil {
fmt.Println(err.Error())
return ""
}
defer conn.Close()
addr := conn.LocalAddr().String()
fmt.Println(addr)
if len(addr) < 0 {
return ""
}
adds := strings.Split(addr, ":")
if len(adds) < 1 {
return ""
}
return adds[0]
}
「真诚赞赏,手留余香」
真诚赞赏,手留余香
使用微信扫描二维码完成支付