一 golang对etcd的增删改查
package main
import (
"context"
"fmt"
"github.com/etcd-io/etcd/clientv3"
"time"
)
func connect() (client *clientv3.Client, err error){
client, err = clientv3.New(clientv3.Config{
Endpoints: []string{"127.0.0.1:2379", "127.0.0.1:22379", "127.0.0.1:32379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("connect err:", err)
return nil, err
}
return client, err
}
func main() {
cli, err := connect()
defer cli.Close()
if err != nil {
return
}
kv := clientv3.NewKV(cli)
r1, err := kv.Put(context.TODO(), "/lesson/math", "100")
if err != nil {
fmt.Println("put key1 err:", err)
return
}
r2, err := kv.Put(context.TODO(), "/lesson/music", "50")
if err != nil {
fmt.Println("put key2 err:", err)
return
}
fmt.Println("添加结果r1: ", r1)
fmt.Println("添加结果r2: ", r2)
getAll, err := kv.Get(context.TODO(), "/lesson/", clientv3.WithPrefix())
if err != nil {
fmt.Println("select all err: ", err)
return
}
fmt.Println("查询所有:", getAll.Kvs)
delResult, err := kv.Delete(context.TODO(), "/lesson/music")
if err != nil {
fmt.Println("del key2 err:", err)
return
}
fmt.Println("删除r2结果:", delResult)
updRerulst, err := kv.Put(context.TODO(), "/lesson/math", "30")
if err != nil {
fmt.Println("upd key2 err:", err)
return
}
fmt.Println("修改r1结果:", updRerulst)
getR1, err := kv.Get(context.TODO(), "/lesson/math")
if err != nil {
fmt.Println("select r1 err: ", err)
return
}
fmt.Println("查询r1结果:", getR1.Kvs)
getR2, err := kv.Get(context.TODO(), "/lesson/music")
if err != nil {
fmt.Println("select r2 err: ", err)
return
}
fmt.Println("查询r2结果:", getR2.Kvs)
}
二 批量操作
- 批量删除:
kv.Delete(context.TODO(), "/lesson/", clientv3.WithPrevfix())
- 批量按顺序删除,并删除2个:
kv.Delete(context.TODO(), "/lesson/lesson1", clientv3.WithFromKey(),clientv3.WithLimit(2))
三 使用OP操作代替原有的增删改查
putOp := clientv3.OpPut("/cron/jobs/job8", "888")
opR, err := kv.Do(context.TODO(), putOp)
if err != nil {
fmt.Println("putOp err:", err)
return
}
fmt.Println("写入Revision:", opR.Put().Header.Revision)
getOp := clientv3.OpGet("/cron/jobs/job8")
opR2, err := kv.Do(context.TODO(), getOp)
if err != nil {
fmt.Println("getOp err:", err)
return
}
fmt.Println("获取Revisoon:", opR2.Get().Kvs[0].ModRevision)
fmt.Println("获取Value:", opR2.Get().Kvs[0].Value)