前置操作:
需要先下载按照client/v3的bao
go get go.etcd.io/etcd/client/v3
1、初始化客户端
package mainimport ("context""log"clientv3 "go.etcd.io/etcd/client/v3""time"
)var cli *clientv3.Client
func init() {// 初始化etcd客户端var err errorcli, err = clientv3.New(clientv3.Config{Endpoints: []string{"127.0.0.1:2379"}, // 替换为你的etcd集群地址DialTimeout: 5 * time.Second,})if err != nil {log.Fatal(err)}
}
etcdkv_38">2、向etcd写入kv对
// put 向etcd写入数据
func put(key, value string) {response, err := cli.Put(context.Background(), key, value)if err != nil {log.Fatal(err)}log.Printf("write data success,response header is:%s", response.Header.String())
}
etcdkv_51">3、从etcd中读取kv对
使用精确的key获取以及基于前缀方式的获取
// get 获取指定的key数据
func get(key string) {response, err := cli.Get(context.Background(), key)if err != nil {log.Fatal(err)}log.Printf("get data success,response header is:%s, count is:%d", response.Header.String(), response.Count)for _, kv := range response.Kvs {log.Printf("k:%s,value:%s,version:%d, CreateRevision :%d", string(kv.Key), string(kv.Value), kv.Version, kv.CreateRevision)}
}// getValueByPrefix 获取以key开头的数据
func getValueByPrefix(key string) {response, err := cli.Get(context.Background(), key, clientv3.WithPrefix())if err != nil {log.Fatal(err)}log.Printf("get value by prefix data success,response header is:%s", response.Header.String())for _, kv := range response.Kvs {log.Printf("k:%s,value:%s,version:%s", string(kv.Key), string(kv.Value), kv.Version)}
}
etcdkey_81">4、从etcd中更新key
// update 更新key
func update(key, value string) {put(key, value)
}
etcdkey_92">5、从etcd中删除key
func delete(key string, other_key ...string) {response, err := cli.Delete(context.TODO(), key)if err != nil {log.Fatal(err)}log.Printf("delete key success,response header is:%s", response.Header.String())for _, k := range other_key {response, err = cli.Delete(context.TODO(), k)if err != nil {log.Fatal(err)}log.Printf("delete key success,response header is:%s", response.Header.String())}
etcdkey_110">6、监视etcd中key的变化
// watch 监视key的变化
func watch(key string) {// 启动一个 WatcherwatchChan := cli.Watch(context.Background(), key)for watchResp := range watchChan {for _, event := range watchResp.Events {switch event.Type {case mvccpb.PUT:if event.IsCreate() {fmt.Printf("[新增] Key: %s, Value: %s\n", event.Kv.Key, event.Kv.Value)} else {fmt.Printf("[更新] Key: %s, Value: %s\n", event.Kv.Key, event.Kv.Value)}case mvccpb.DELETE:fmt.Printf("[删除] Key: %s\n", event.Kv.Key)}}}
}
package mainimport ("context""log"clientv3 "go.etcd.io/etcd/client/v3""time"
)var cli *clientv3.Clientfunc main() {defer cli.Close()key1 := "key1"key2 := "key2"put(key1, "value1")put(key2, "value2")get(key1)getValueByPrefix("key")update(key1, "value_updated")delete(key1, key2)
}}func init() {// 初始化etcd客户端var err errorcli, err = clientv3.New(clientv3.Config{Endpoints: []string{"127.0.0.1:2379"}, // 替换为你的etcd集群地址DialTimeout: 5 * time.Second,})if err != nil {log.Fatal(err)}
}