1.安装
https://www.cnblogs.com/chenqionghe/p/10503840.html
启动
#!/bin/bash
nohup ./etcd -listen-client-urls="http://0.0.0.0:2379" --advertise-client-urls="http://0.0.0.0:2379" &
-- name=bbim
etcdctl memberlist list 显示信息
命令:
删除所有的 etcdctl del --prefix ""
etcdctl默认是V2版本,etcdkeeper如果是用V3创建的,则获取不到,也要指定V2版本,可以把ETCDCTL_API=3加入环境变量
ETCDCTL_API=3 ./etcdctl get wo
获取所有key etcdctl get --prefix ""
如:
[root@VM_0_13_centos etcd-v3.3.12-linux-amd64]# ETCDCTL_API=2 ./etcdctl --endpoints http://127.0.0.1:2379 get mytest
2.
endpoint.go:114:78: undefined: resolver.BuildOption
gomod中指定使用1.26版本: google.golang.org/grpc v1.26.0 // indirect
3.CRUD
package main
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"time"
)
func main() {
client, err := clientv3.New(clientv3.Config{
Endpoints: []string{"118.89.177.83:2379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
fmt.Println("connect failed, err :", err)
return
}
defer client.Close()
//控制超时
ctx, mycancel := context.WithTimeout(context.Background(), time.Second * 10)
//1. 增-存值
timeStr:=time.Now().Format("2006-01-02 15:04:05")
fmt.Printf("begin with %s\n", timeStr)
_, err = client.Put(ctx, "/demo/demo1_key", "demo1_value")
_, err = client.Put(ctx, "/demo/demo2_key", "demo2_value")
_, err = client.Put(ctx, "/demo/demo3_key", "demo3_value")
//操作完毕,cancel掉
timeStr = time.Now().Format("2006-01-02 15:04:05")
fmt.Printf("end with %s \n", timeStr)
//Context
mycancel()
if err != nil {
fmt.Println("put failed, err:", err)
return
}
//2. 查-获取值, 也设置超时
ctx, mycancel = context.WithTimeout(context.Background(), time.Second * 30)
//resp, err := client.Get(ctx, "/demo")
// Get查询还可以增加WithPrefix选项,获取某个目录下的所有子元素,可以匹配/demo***, /demo/***, /demo/***/***
resp, err := client.Get(ctx, "/demo", clientv3.WithPrefix())
mycancel()
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)
presp, err1 := client.Put(ctx, "/demo/demo1_key", "update_value", clientv3.WithPrevKV())
if err1 != nil {
fmt.Println("get failed err: ", err)
}
fmt.Println(string(presp.PrevKv.Value))
//4. 删-删除值
ctx, _ = context.WithTimeout(context.Background(), time.Second)
dresp, err2 := client.Delete(ctx, "/demo/demo1_key")
if err2 != nil {
fmt.Println(err)
}
fmt.Println(dresp.PrevKvs)
}