etcd 使用: golang 例子

本文内容纲要:

- 一:连接到 etcd

- 二:KV操作:增 删 改 查

- 三:watch 监听

- 四:Transaction 事务

- 五:lease 租约

一:连接到 etcd

package main

import (

"fmt"

"go.etcd.io/etcd/clientv3"

"time"

)

//连接

func main() {

//客户端配置

config := clientv3.Config{

Endpoints: []string{"192.168.1.109:2379"},

DialTimeout: 5 * time.Second,

}

//建立连接

if client, err := clientv3.New(config); err != nil {

fmt.Println(err)

return

}

fmt.Println("connect success")

defer client.Close()

}

Endpoints:etcd的多个节点服务地址。

DialTimeout:创建client的首次连接超时时间,这里传了5秒,如果5秒都没有连接成功就会返回err;

一旦client创建成功,我们就不用再关心后续底层连接的状态了,client内部会重连。

二:KV操作:增 删 改 查

package main

import (

"context"

"fmt"

"go.etcd.io/etcd/clientv3"

"time"

)

func main() {

client, err := clientv3.New(clientv3.Config{

Endpoints: []string{"192.168.1.109:2379", "192.168.1.109:2379"},

DialTimeout: 5 * time.Second,

})

if err != nil {

fmt.Println("connect failed, err :", err)

return

}

defer client.Close()

//控制超时

ctx, cancel := context.WithTimeout(context.Background(), time.Second)

//1. 增-存值

_, err = client.Put(ctx, "/demo/demo1_key", "demo1_value")

//操作完毕,cancel掉

cancel()

if err != nil {

fmt.Println("put failed, err:", err)

return

}

//2. 查-获取值, 也设置超时

ctx, cancel = context.WithTimeout(context.Background(), time.Second)

resp, err := client.Get(ctx, "/demo/demo1_key")

// Get查询还可以增加WithPrefix选项,获取某个目录下的所有子元素

//eg: resp, err := client.Get(ctx, "/demo/", clientv3.WithPrefix())

cancel()

if err != nil {

fmt.Println("get failed err:", err)

return

}

for _, item := range resp.Kvs { //Kvs 返回key的列表

fmt.Printf("%s : %s \n", item.Key, item.Value)

}

//3. 改-修改值

ctx, _ = context.WithTimeout(context.Background(), time.Second)

resp, err := client.Put(ctx, "/demo/demo1_key", "update_value", clientv3.WithPrevKV()))

if err != nil {

fmt.Println("get failed err: ", err)

}

fmt.Println(string(resp.PrevKv.Value))

//4. 删-删除值

ctx, _ = context.WithTimeout(context.Background(), time.Second)

resp, err := client.Delete(ctx, "/demo/demo1_key")

if err != nil {

fmt.Println(err)

}

fmt.Println(resp.PrevKvs)

}

三:watch 监听

package main

import (

"context"

"fmt"

"go.etcd.io/etcd/clientv3"

"time"

)

func main() {

client, err := clientv3.New(clientv3.Config{

Endpoints: []string{"192.168.1.109:2379"},

DialTimeout: time.Second,

})

if err != nil {

fmt.Println("connect failed err : ", err)

return

}

defer client.Close()

client.Put(context.Background(), "/demo/demo2_key", "demo2_value")

go func() {

//watch

watchKey := client.Watch(context.Background(), "/demo/demo2_key")

for resp := range watchKey {

for _, item := range resp {

fmt.Printf("%s %q : %q \n", item.Type, item.Kv.key, item.Kv.Value)

}

}

}

if resp, err := client.Put(context.TODO(), "/demo/demo2_key/", "demo2_watch"); err != nil {

fmt.Println(err)

} else {

fmt.Println(resp)

}

}

四:Transaction 事务

package main

import (

"context"

"fmt"

"go.etcd.io/etcd/clientv3"

"log"

"sync"

"time"

)

func main() {

client, err := clientv3.New(clientv3.Config{

Endpoints: 5 * time.Second,

DialTimeout: 3 * time.Second,

})

if err != nil {

fmt.Println("connect failed err: ", err)

return

}

client.Close()

var w sync.WaitGroup

w.Add(10)

key10 := "setnx"

for i := 0; i < 10; i++ {

go func(i int) {

time.Sleep(5 * time.Millisecond)

//通过key的Create_Revision 是否为 0 来判断key是否存在。其中If,Then 以及 Else 分支都可以包含多个操作。

//返回的数据包含一个successed字段,当为 true 时代表 If 为真

_, err := client.Txn(context.Background()).

If(clientv3.Compare(clientv3.CreateRevision(key10), "=", 0)).

Then(clientv3.OpPut(key10, fmt.Sprintf("%d", i))).

Commit()

if err != nil {

fmt.Println(err)

}

w.Done()

}(i)

}

w.Wait()

if resp, err := client.Get(context.TODO(), key10); err != nil {

log.Fatal(err)

} else {

log.Println(resp)

}

}

五:lease 租约

package main

import (

"time"

)

//From:https://github.com/the-gigi/go-etcd3-demo/blob/master/main.go

var (

dialTimeout = 2 * time.Second

requestTimeout = 10 * time.Second

)

func main() {

ctx, _ := context.WithTimeout(context.Background(), requestTimeout)

client, err := clientv3.New(clientv3.Config{

DialTimeout: dialTimeout,

Endpoints: []string{"localhost:2379"},

})

if err != nil {

log.Fatal(err)

}

kv := clientv3.NewKv(client)

//Delete all keys

kv.Delete(ctx, "/demo/demo1_key", clientv3.WithPrefix())

gr, _ := kv.Get(ctx, "/demo/demo1_key")

if len(gr.Kvs) == 0 {

fmt.Println("no key")

}

lease, err := client.Grant(ctx, 3)

if err != nil {

log.Fatal(err)

}

//Insert key with a lease of 3 second TTL

kv.Put(ctx, "/demo/demo1_key", "demo1_value", clientv3.WithLease(lease.ID))

gr, _ = kv.Get(ctx, "/demo/demo1_key")

if len(gr.Kvs) == 1 {

fmt.Println("Found key")

}

//let the TTL expire

time.Sleep(3 * time.Second)

gr, _ = kv.Get(ctx, "/demo/demo1_key")

if len(gr.Kvs) == 0 {

fmt.Println("no more key")

}

}

//From:https://github.com/the-gigi/go-etcd3-demo/blob/master/main.go

本文内容总结:一:连接到 etcd,二:KV操作:增 删 改 查,三:watch 监听,四:Transaction 事务,五:lease 租约,

原文链接:https://www.cnblogs.com/jiujuan/p/10930664.html

以上是 etcd 使用: golang 例子 的全部内容, 来源链接: utcz.com/z/297038.html

回到顶部