clientv3.New() 创建连接
config = ec.Config{
Endpoints: []string{"10.0.0.5:2379"}, //连接的etcd集群地址,这里为单机的故一个地址
DialTimeout: 30 * time.Second, //超时时长
}
返回值为clientv3.Client结构体

KV是经常使用的类型,主要用来操作key value值
client.Put() 实际上就是KV接口实现的一个方法

KV.Put 向etcd中插入一个Key,如存在则替换新的值。
if putRes, err = kv.Put(context.TODO(), "/cron/jobs/job3", "test111111 hel3123lo",ec.WithPrevKV()); err != nil {
fmt.Println(err)
} else {
fmt.Println("revision: ", putRes.Header.Revision)
if putRes.PrevKv != nil{
fmt.Println(string(putRes.PrevKv.Value))
}
}
WithPrevKV()获取Put事件操作之前的键值对



package main
import (
"context"
"fmt"
"time"
ec "go.etcd.io/etcd/clientv3"
)
func main() {
var (
config ec.Config
client *ec.Client
err error
kv ec.KV
putRes *ec.PutResponse
)
config = ec.Config{
Endpoints: []string{"10.0.0.5:2379"},
DialTimeout: 30 * time.Second,
}
if client, err = ec.New(config); err != nil {
fmt.Println(err)
return
}
kv = ec.NewKV(client)
if putRes, err = kv.Put(context.TODO(), "/cron/jobs/job3", "test111111 hel3123lo",ec.WithPrevKV()); err != nil {
fmt.Println(err)
} else {
fmt.Println("revision: ", putRes.Header.Revision)
if putRes.PrevKv != nil{
fmt.Println(string(putRes.PrevKv.Value))
}
}
op:= ec.OpGet("/cron/jobs/job3")
fmt.Println(string(op.KeyBytes()))
}

如果Key不存在,则没有事件操作之前的信息

[root@node01 ~]# ETCDCTL_API=3 etcdctl get /cron/jobs/ --prefix /cron/jobs/job1 test hello /cron/jobs/job2 test111111 hel3123lo /cron/jobs/job3 test22222 hello2222 /cron/jobs/job4 test22222 hello2222
原文:https://www.cnblogs.com/LC161616/p/10380601.html