go操作etcd

作者: ropon 分类: Go 发布时间: 2020-07-07 13:41
package main

import (
    "context"
    "crypto/tls"
    "crypto/x509"
    "fmt"
    "io/ioutil"
    "log"
    "time"

    "go.etcd.io/etcd/clientv3"
)

// etcd client put/get demo
// use etcd/clientv3

func main() {
    //使用https链接etcd
    var etcdCert = "./etcd.pem"
    var etcdCertKey = "./etcd-key.pem"
    var etcdCa = "./ca.pem"

    cert, err := tls.LoadX509KeyPair(etcdCert, etcdCertKey)
    if err != nil {
        return
    }

    caData, err := ioutil.ReadFile(etcdCa)
    if err != nil {
        return
    }

    pool := x509.NewCertPool()
    pool.AppendCertsFromPEM(caData)

    _tlsConfig := &tls.Config{
        Certificates: []tls.Certificate{cert},
        RootCAs:      pool,
    }
    cli, err := clientv3.New(clientv3.Config{
        Endpoints:   []string{"https://192.168.7.150:2379"},
        DialTimeout: 5 * time.Second,
        TLS:         _tlsConfig,
    })
    if err != nil {
        // handle error!
        fmt.Printf("connect to etcd failed, err:%v\n", err)
        return
    }
    fmt.Println("connect to etcd success")
    defer cli.Close()
    //// put
    //ctx, cancel := context.WithTimeout(context.Background(), time.Second)
    //_, err = cli.Put(ctx, "ropon", "666")
    //cancel()
    //if err != nil {
    //  fmt.Printf("put to etcd failed, err:%v\n", err)
    //  return
    //}
    //// get
    //ctx, cancel = context.WithTimeout(context.Background(), time.Second)
    //resp, err := cli.Get(ctx, "ropon")
    //cancel()
    //if err != nil {
    //  fmt.Printf("get from etcd failed, err:%v\n", err)
    //  return
    //}
    //for _, ev := range resp.Kvs {
    //  fmt.Printf("%s:%s\n", ev.Key, ev.Value)
    //}

    //// watch key:q1mi change
    //rch := cli.Watch(context.Background(), "west") // <-chan WatchResponse
    //for wresp := range rch {
    //  for _, ev := range wresp.Events {
    //      fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
    //  }
    //}

    // 创建一个5秒的租约
    resp, err := cli.Grant(context.TODO(), 5)
    if err != nil {
        log.Fatal(err)
    }

    // 5秒钟之后, /ropon/ 这个key就会被移除
    _, err = cli.Put(context.TODO(), "/ropon/", "8888", clientv3.WithLease(resp.ID))
    if err != nil {
        log.Fatal(err)
    }

    // the key 'foo' will be kept forever
    ch, kaerr := cli.KeepAlive(context.TODO(), resp.ID)
    if kaerr != nil {
        log.Fatal(kaerr)
    }
    for {
        ka := <-ch
        fmt.Println("ttl:", ka.TTL)
    }
}

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!