Etcd-clientV3-使用TLS证书存取KV

57次阅读

共计 2022 个字符,预计需要花费 6 分钟才能阅读完成。

为了保证数据传输的安全行 Etcd clientV3 提供了通过 tls,https 通讯。
通过 tls.Config 可以轻松实现。具体看如下示例代码就能理解

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "time"

    "crypto/tls"
    "crypto/x509"

    "go.etcd.io/etcd/clientv3"
    "golang.org/x/net/context"
)

var (
    dialTimeout    = 5 * time.Second
    requestTimeout = 4 * time.Second
    endpoints      = []string{"https://172.17.84.204:2379", "https://172.17.84.205:2379", "https://172.17.84.206:2379"}
)

func main() {

    var etcdCert = "./ca/etcd-client.pem"
    var etcdCertKey = "./ca/etcd-client-key.pem"
    var etcdCa = "./ca/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,
    }

    cfg := clientv3.Config{
        Endpoints: endpoints,
        TLS:       _tlsConfig,
    }

    cli, err := clientv3.New(cfg)

    if err != nil {log.Fatal(err)
    }

    defer cli.Close()

    key1, value1 := "testkey1", "value"

    ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
    _, err = cli.Put(ctx, key1, value1)
    cancel()
    if err != nil {log.Println("Put failed.", err)
    } else {log.Printf("Put {%s:%s} succeed\n", key1, value1)
    }

    ctx, cancel = context.WithTimeout(context.Background(), requestTimeout)
    resp, err := cli.Get(ctx, key1)
    cancel()
    if err != nil {log.Println("Get failed.", err)
        return
    }

    for _, kv := range resp.Kvs {log.Printf("Get {%s:%s} \n", kv.Key, kv.Value)
    }

    done := make(chan bool)

    go func() {wch := cli.Watch(context.Background(), key1)

        for item := range wch {
            for _, ev := range item.Events {log.Printf("Type:%s, key:%s, value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
            }
        }
    }()

    go func() {
        for cnt := 0; cnt < 10; cnt++ {value := fmt.Sprintf("%s%d", "value", cnt)
            _, err = cli.Put(context.Background(), key1, value)
            if err != nil {log.Println("Put failed.", err)
            } else {log.Printf("Put {%s:%s} succeed\n", key1, value)
            }
        }
    }()

    <-done

    log.Println("Done!")
}
  • 注意事项

    <1> etcd 主机使用 https

    endpoints      = []string{"https://172.17.84.204:2379", "https://172.17.84.205:2379", "https://172.17.84.206:2379"}

    <2> 公私钥文件

    var etcdCert = "./ca/etcd-client.pem"
    var etcdCertKey = "./ca/etcd-client-key.pem"
    var etcdCa = "./ca/ca.pem"

    <3> requestTimeout 时间不要设得太短
    之前 requestTimeout 设置为 2 秒,在 put 时一直失败,查了半天找不出原因,改成 4 秒就好了

正文完
 0