Golang简单操作etcd

2020-11-07  本文已影响0人  FredricZhu

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
上一篇下一篇

猜你喜欢

热点阅读