[GO]go使用etcd

package main

import (
    "go.etcd.io/etcd/clientv3"  //笔者在使用clientv3的时间曾经使用过github.com/coreos/etcd/clientv3这个包,但是会报错,改成这个包就没有问题
    "time"
    "context"
    "fmt"
)

func main() {
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:[]string{"localhost:2379", "localhost:22379", "localhost:32379"},
        DialTimeout:5*time.Second,
    })
    if err != nil {
        //
    }
    defer cli.Close()

    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    _, err = cli.Put(ctx, "/logagent/conf/", "bbb")
    cancel()
    if err != nil {
        fmt.Println("err:", err)
    }

    ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second)
    resp, err := cli.Get(ctx, "/logagent/conf/")
    cancel()
    if err != nil {
        fmt.Println("get failed, err:", err)
        return
    }
    for _, ev := range resp.Kvs{
        fmt.Printf("%s:%s
", ev.Key, ev.Value)
    }
}
原文地址:https://www.cnblogs.com/baylorqu/p/9996258.html