(摘) golang操作Etcd数据库

声明:内容源自网络,版权归原作者所有。若有侵权请在网页聊天中联系我

原文:https://blog.csdn.net/qq_43716830/article/details/124180951

put与get

package main

import (
	"context"
	"fmt"
	"time"

	"go.etcd.io/etcd/clientv3"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"}, //节点
		DialTimeout: 5 * time.Second,            //超过5秒钟连不上超时
	})
	if err != nil {
		fmt.Println("connect to etcd failed:", err)
		return
	}
	fmt.Println("connect to etcd success")
	defer cli.Close()
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err = cli.Put(ctx, "zyj", "dsb")
	cancel()
	if err != nil {
		fmt.Println("put to etcd failed,err:", err)
		return
	}
	ctx, cancel = context.WithTimeout(context.Background(), time.Second)
	resp, err := cli.Get(ctx, "zyj") //resp是相应对象
	cancel()
	if err != nil {
		fmt.Println("get from etcd failed:", err)
		return
	}
	for _, ev := range resp.Kvs { //Kvs是响应对象的多个键值对
		fmt.Printf("%s:%s\n", ev.Key, ev.Value)
	}
}

watch

package main

import (
	"context"
	"fmt"
	"time"

	"go.etcd.io/etcd/clientv3"
)

func main() {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
	})
	if err != nil {
		fmt.Println("connect to etcd success")
		return
	}
	fmt.Println("connect to etcd success")
	defer cli.Close()
	//派一个哨兵 一直监视着zyj的变化(新增,修改,删除)
	ch := cli.Watch(context.Background(), "zyj")
	//从通道中尝试取值(监视的信息)
	for wresp := range ch {
		for _, evt := range wresp.Events {
			fmt.Printf("Type:%v key:%v value:%v\n", evt.Type, string(evt.Kv.Key), evt.Kv.Value)
		}
	}
}

另一示例:

package main

import (
    "context"
    "fmt"
    "go.etcd.io/etcd/clientv3"
    "strconv"
    "time"
)

func main(){
    //服务列表 切片类型
    endpoints := []string{
        "127.0.0.1:2379",
    }
    client3,err := clientv3.New(
        clientv3.Config{
            Endpoints:            endpoints,
            //你还可以设置更过的参数 如果开启了auth验证 也可以配置username和password
        },
    )
    // conn fail
    if err != nil {
        panic(err.Error())
    }
    // conn success
    // 第一种:etcdctl put  写入
    response, err := client3.Put(context.TODO(), "hello", "hushaoliang&hujiacheng")
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(response)

    fmt.Println("=============================================================================================")

    // 第二种:etcdctl get   获取
    getResponse, err := client3.Get(context.TODO(), "hello")
    if err != nil {
        panic(err.Error())
    }
    for _,kv :=  range getResponse.Kvs {
        fmt.Println(kv)
        fmt.Println(string(kv.Key) + "-------" + string(kv.Value))
    }

    fmt.Println("=============================================================================================")

    // 第三种:etcdctl get --prefix 获取带前缀的key的值
    getAll, err := client3.Get(context.TODO(), "web", clientv3.WithPrefix())
    if err != nil {
        panic(err.Error())
    }
    for _,kv1 := range getAll.Kvs {
        fmt.Println(kv1)
        fmt.Println(string(kv1.Key) + "--------" + string(kv1.Value))
    }

    fmt.Println("=============================================================================================")

    // 第四种:etcdctl del 刪除元素
    deleteResponse, err := client3.Delete(context.TODO(), "hello")
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(deleteResponse)

    fmt.Println("=============================================================================================")

    // 第五种:etcdctl watch 监控一个key的变化
    //通过channel管道进行的监控 所以无时无刻不在监控 所以呢主进程不会死掉的!
    watch := client3.Watch(context.TODO(), "mine")
    for wc := range watch {
        //读取watch返回值里面的事件
        for _,w := range wc.Events {
            fmt.Println(string(w.Kv.Key),string(w.Kv.Value),w.Type.String())
        }
    }

    fmt.Println("=====================程序会卡在这不动 一直监控着watch监控的key值的变化 下边的测试需要你关闭watch监控哈===========================")

    // 第六种:etcdctl lease grant 100 租赁时长是60s 60s之后就自动过期了!
    grantResponse, err := client3.Grant(context.TODO(), 60)
    if err != nil {
        panic(err.Error())
    }
    if _, err := client3.Put(context.TODO(), "wocao", "nidaye", clientv3.WithLease(grantResponse.ID));err != nil {
        panic(err.Error())
    }
    fmt.Println("ok")
    //测试租赁是否成功  租赁时长是60s 60s之后就自动过期了!
    i := 0
    for {
        ps, err := client3.Get(context.TODO(), "wocao")
        if err != nil {
            panic(err.Error())
        }
        for _,kv := range ps.Kvs {
            fmt.Println(string(kv.Key) + "----" + string(kv.Value))
        }
        i += 5
        fmt.Println(strconv.Itoa(i)+"s")
        time.Sleep(5 * time.Second)
    }

    fmt.Println("=============================================================================================")


}

相关文章