etcd中kv存储已经租约和监听的基本使.都说源码之下了无秘密,就不打字了.
```
package main
import (
"context"
"log"
"time"
"go.etcd.io/etcd/clientv3"
)
func main() {
var conf = clientv3.Config{
Endpoints: []string{"127.0.0.1:2380"},
DialTimeout: 5 * time.Second,
}
//创建clinetv3
client, err := clientv3.New(conf)
defer client.Close()
if err != nil {
log.Fatal(err.Error())
}
//创建租约
lease := clientv3.NewLease(client)
//设置租约时间
leaseResp, err := lease.Grant(context.TODO(), 30)
if err != nil {
log.Fatal(err.Error())
}
//设置续租
leaseID := leaseResp.ID
ctx, _ := context.WithCancel(context.TODO())
leaseRespChan, err := lease.KeepAlive(ctx, leaseID)
if err != nil {
log.Fatal(err.Error()) //设置续租失败 续期之后向leaseRespChan通知
}
//监听租约
go func() {
for {
select {
case resp := <-leaseRespChan:
if resp == nil {
log.Println("租约已经到期关闭")
goto LEASE_OVER
} else {
log.Println("续租成功")
goto END
}
}
LEASE_OVER:
log.Println("lease 监听结束")
break
END:
time.Sleep(500 * time.Millisecond)
}
}()
//监听某个key的变化
//ctx1, _ := context.WithTimeout(context.TODO(),20)
go func() {
wc := client.Watch(context.TODO(), "/job/v3/1", clientv3.WithPrevKV()) //创建监听
for v := range wc { //range 监听事件
for _, e := range v.Events {
log.Printf("type:%v kv:%v prevKey:%v \n ", e.Type, string(e.Kv.Key), e.PrevKv)
}
}
}()
//key授权租约
kv := clientv3.NewKV(client)
//通过租约put
putResp, err := kv.Put(context.TODO(), "/job/v3/1", "koock", clientv3.WithLease(leaseID))
if err != nil {
log.Printf("put 失败:%s", err.Error())
}
log.Printf("%v\n", putResp.Header)
time.Sleep(10 * time.Second)
//撤销租约
_, err = lease.Revoke(context.TODO(), leaseID)
if err != nil {
log.Fatalf("撤销租约失败:%s\n", err.Error())
}
log.Println("撤销租约成功")
//cancelFunc()
//查询key
getResp, err := kv.Get(context.TODO(), "/job/v3/1")
if err != nil {
log.Fatalf("get 失败:%s", err.Error())
}
log.Printf("%v", getResp.Kvs)
time.Sleep(20 * time.Second)
}
```
有疑问加站长微信联系(非本文作者))