为了保证数据传输的安全行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!")
}
- 注意事项
-
etcd主机使用https
endpoints = []string{"https://172.17.84.204:2379", "https://172.17.84.205:2379", "https://172.17.84.206:2379"}
-
公私钥文件
var etcdCert = "./ca/etcd-client.pem" var etcdCertKey = "./ca/etcd-client-key.pem" var etcdCa = "./ca/ca.pem"
- requestTimeout时间不要设得太短
之前requestTimeout设置为2秒,在put时一直失败,查了半天找不出原因,改成4秒就好了。
- export ETCDCTL_API=3
有疑问加站长微信联系(非本文作者)