首页 > 其他 > 详细

golang etcdclientv3使用说明

时间:2019-02-14 20:55:45      阅读:1471      评论:0      收藏:0      [点我收藏+]

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

 

golang etcdclientv3使用说明

原文:https://www.cnblogs.com/LC161616/p/10380601.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!