美文网首页
Golang简单操作etcd

Golang简单操作etcd

作者: FredricZhu | 来源:发表于2020-11-07 11:54 被阅读0次

    go.mod文件内容

    module github.com/zhuge20100104/laonanhai/etcddemo
    
    go 1.15
    
    require (
        github.com/coreos/etcd v3.2.30+incompatible
        github.com/coreos/go-semver v0.3.0 // indirect
        github.com/golang/protobuf v1.4.3 // indirect
        golang.org/x/net v0.0.0-20201031054903-ff519b6c9102 // indirect
        google.golang.org/genproto v0.0.0-20201105153401-9d023cd09d72 // indirect
    )
    

    main.go文件内容

    package main
    
    import (
        "context"
        "fmt"
        "time"
    
        "github.com/coreos/etcd/clientv3"
    )
    
    func main() {
        cli, err := clientv3.New(clientv3.Config{
            Endpoints:   []string{"localhost:2379", "localhost:22379", "localhost:32379"},
            DialTimeout: time.Duration(5) * time.Second,
        })
    
        if err != nil {
            fmt.Println("connect failed, err", err)
            return
        }
    
        fmt.Println("connect success")
        defer cli.Close()
        ctx, cancel := context.WithTimeout(context.Background(), time.Second)
        _, err = cli.Put(ctx, "key", "simple value")
        cancel()
        if err != nil {
            fmt.Println("put failed, err: ", err)
            return
        }
    
        ctx, cancel = context.WithTimeout(context.Background(), time.Second)
        resp, err := cli.Get(ctx, "key")
        cancel()
    
        if err != nil {
            fmt.Println("get failed, err: ", err)
            return
        }
        for _, ev := range resp.Kvs {
            fmt.Printf("%s, %s\n", ev.Key, ev.Value)
        }
    }
    

    程序输出如下


    图片.png

    相关文章

      网友评论

          本文标题:Golang简单操作etcd

          本文链接:https://www.haomeiwen.com/subject/xsvtbktx.html