1、启动服务端
2、 设置版本set ETCDCTL_API=3
3、使用客户端命令操作:
4、代码操作etcdctl put key1 value1 成功返回OK
1、向etcd中put,set
package main
import (
"context"
"encoding/json"
"fmt"
"time"
"github.com/coreos/etcd/clientv3"
)
const (
EtcdKey = "/tcy/backend/logAgent/config/192.168.238.1"
)
type LogConf struct {
Path string `json:"path"`
Topic string `json:"topic"` //写到哪个topic下面
}
func SetLogConfToEtcd() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
var logConfArr []LogConf
logConfArr = append(
logConfArr,
LogConf{
Path: "./day12/etcd_example/logs/access.log",
Topic: "topic01",
},
)
logConfArr = append(
logConfArr,
LogConf{
Path: "./day12/etcd_example/logs/error.log",
Topic: "topic01",
},
)
data, err := json.Marshal(logConfArr)
if err != nil {
fmt.Println("json failed, ", err)
return
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err = cli.Put(ctx, EtcdKey, string(data))
cancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
resp, err := cli.Get(ctx, EtcdKey)
cancel()
if err != nil {
fmt.Println("get failed, err:", err)
return
}
for _, ev := range resp.Kvs {
fmt.Printf("%s : %s\n", ev.Key, ev.Value)
}
}
func main() {
SetLogConfToEtcd()
//EtcdExmaple()
}
func EtcdExmaple() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 100 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err = cli.Put(ctx, "/logagent/conf/", "sample_value")
cancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second)
resp, err := cli.Get(ctx, "/logagent/conf/")
cancel()
if err != nil {
fmt.Println("get failed, err:", err)
return
}
for _, ev := range resp.Kvs {
fmt.Printf("%s : %s\n", ev.Key, ev.Value)
}
}
connect succ
/tcy/backend/logAgent/config/192.168.238.1 : [{"path":"./day12/etcd_example/logs/access.log","topic":"topic01"},{"path":"./day12/etcd_example/logs/error.log","topic":"topic01"}
2、watch监听
func main() {
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379"},
DialTimeout: 10 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err:", err)
return
}
fmt.Println("connect succ")
defer cli.Close()
cli.Put(context.Background(), "/logagent/conf/", "2222222222")
for {
rch := cli.Watch(context.Background(), "/logagent/conf/") //到这里就会停下,一直监听。
for wresp := range rch {
for _, ev := range wresp.Events {
fmt.Printf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}
}
}
结果:
1、处于监听状态:
2、修改etcd中的key值,etcd可以监听到了。