1. 程式人生 > 實用技巧 >GO-操作etcd簡單示例

GO-操作etcd簡單示例

go操作etcd

etcd是使用Go語言開發的一個開源的、高可用的分散式key-value儲存系統,可以用於配置共享和服務的註冊和發現。

建立測試專案

  • 建立專案go mod init goetcd
  • 下載go依賴庫sarama go get go.etcd.io/etcd/clientv3

注意事項

  • 在windows平臺上下載安裝clientv3出錯(因grpc v1.27.0+版本的google.golang.org/grpc包不支援etcdv3引起的)

解決辦法修改依賴版本

#修改依賴
go mod edit -require=google.golang.org/[email protected]

或在go.mod里加上

replace google.golang.org/grpc => google.golang.org/grpc v1.26.0

操作

put和get操作

put命令用來設定鍵值對資料,get命令用來根據key獲取值。

package main

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

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

var (
	dialTimeout    = 5 * time.Second
	requestTimeout = 4 * time.Second
	endpoints      = []string{"https://192.168.10.190:2379", "https://192.168.10.191:2379", "https://192.168.10.192:2379"}
	etcdCert       = "etcd.pem"
	etcdCertKey    = "etcd-key.pem"
	etcdCa         = "ca.pem"
)

func main() {
	// 建立連線-TLS
	cert, err := tls.LoadX509KeyPair(etcdCert, etcdCertKey)
	if err != nil {
		fmt.Printf("cert failed, err:%v\n", err)
		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,
		DialTimeout: dialTimeout,
		TLS:         _tlsConfig,
	}

	cli, err := clientv3.New(cfg)

	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(), requestTimeout)
	_, err = cli.Put(ctx, "標", "hello")
	cancel()
	if err != nil {
		fmt.Printf("put to etcd failed, err:%v\n", err)
		return
	}

	// get
	ctx, cancel = context.WithTimeout(context.Background(), requestTimeout)
	resp, err := cli.Get(ctx, "標")
	cancel()

	if err != nil {
		fmt.Printf("get from etcd failed, err:%v\n", err)
		return
	}

	for _, kv := range resp.Kvs {
		fmt.Printf("%s:%s\n", kv.Key, kv.Value)
	}
}
  • 執行結果