etcd做注册服务使用 类似java生态的zookeeper,最近在学学习
1、下载etcd包
//直接下载即可(因为包比较大有翻墙,可以直接去 https://golangtc.com/download/package 下载)
go get go.etcd.io/etcd/clientv3
2、使用记录
packge main
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
//"log/syslog"
"time"
)
func main() {
var (
config clientv3.Config
client *clientv3.Client
err error
kv clientv3.KV
putResp *clientv3.PutResponse
getResp *clientv3.GetResponse
delResp *clientv3.DeleteResponse
keepResp *clientv3.LeaseKeepAliveResponse
keepRespChan <-chan *clientv3.LeaseKeepAliveResponse
)
}
//客户端配置
config = clientv3.Config{
Endpoints:[]string{"127.0.0.1:2379"},
DialTimeout:5 * time.Second,
}
//建立连接
if client,err = clientv3.New(config);err != nil {
fmt.Println(err)
return
}
//得到操作etcd键值对的kv
kv = clientv3.NewKV(client)
//写入etcd
if putResp,err = kv.Put(context.TODO(),"/cron/jobs/job2","....",clientv3.WithPrevKV()/*可选参数,得到上次操作的值*/);err != nil {
fmt.Println(err)
} else {
fmt.Println(putResp.Header.Revision)
if putResp.PrevKv != nil {
fmt.Println(string(putResp.PrevKv.Value))
}
}
//读取某个key的value值
getResp,err = kv.Get(context.TODO(),"/cron/jobs/job1"/*,clientv3.WithCountOnly()可选参数,得到数量*/)
if err != nil {
fmt.Println(err)
return
} else {
fmt.Println(getResp.Kvs[0].Value/*得到的是一个切片*/)
}
//读取前缀为XXX的所有的key的value(需要加上参数clientv3.WithPrefix())
if getResp,err = kv.Get(context.TODO(),"/cron/jobs/",clientv3.WithPrefix());err != nil {
fmt.Println(err)
return
} else {
fmt.Println(getResp.Kvs)
}
//删除操作
if delResp,err = kv.Delete(context.TODO(),"/cron/jobs/job2",clientv3.WithPrevKV()/*得到删除之前的值*/);err != nil {
fmt.Println(err)
return
} else {
if len(delResp.PrevKvs) != 0 {
fmt.Println(delResp.PrevKvs)
}
}
网友评论