etcd通信接口之客戶端API核心方法實戰(zhàn)
前言
我們在前面介紹了 etcd 的整體架構。學習客戶端與 etcd 服務端的通信以及 etcd 集群節(jié)點的內部通信接口對于我們更好地使用和掌握 etcd 組件很有幫助,也是所必需了解的內容。我們將會介紹 etcd 的 gRPC 通信接口以及客戶端的實踐。
etcd clientv3 客戶端
etcd 客戶端 clientv3 接入的示例將會以 Go 客戶端為主,讀者需要準備好基本的開發(fā)環(huán)境。
首先是 etcd clientv3 的初始化,我們根據(jù)指定的 etcd 節(jié)點,建立客戶端與 etcd 集群的連接。
cli,err := clientv3.New(clientv3.Config{
Endpoints:[]string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
如上的代碼實例化了一個 client,這里需要傳入的兩個參數(shù):
- Endpoints:etcd 的多個節(jié)點服務地址,因為我是單點本機測試,所以只傳 1 個。
- DialTimeout:創(chuàng)建 client 的首次連接超時,這里傳了 5 秒,如果 5 秒都沒有連接成功就會返回 err;值得注意的是,一旦 client 創(chuàng)建成功,我們就不用再關心后續(xù)底層連接的狀態(tài)了,client 內部會重連。
etcd 客戶端初始化
解決完包依賴之后,我們初始化 etcd 客戶端。客戶端初始化代碼如下所示:
// client_init_test.go
package client
import (
"context"
"fmt"
"go.etcd.io/etcd/clientv3"
"testing"
"time"
)
// 測試客戶端連接
func TestEtcdClientInit(t *testing.T) {
var (
config clientv3.Config
client *clientv3.Client
err error
)
// 客戶端配置
config = clientv3.Config{
// 節(jié)點配置
Endpoints: []string{"localhost:2379"},
DialTimeout: 5 * time.Second,
}
// 建立連接
if client, err = clientv3.New(config); err != nil {
fmt.Println(err)
} else {
// 輸出集群信息
fmt.Println(client.Cluster.MemberList(context.TODO()))
}
client.Close()
}
如上的代碼,預期的執(zhí)行結果如下:
=== RUN TestEtcdClientInit
&{cluster_id:14841639068965178418 member_id:10276657743932975437 raft_term:3 [ID:10276657743932975437 name:"default" peerURLs:"http://localhost:2380" clientURLs:"http://0.0.0.0:2379" ] {} [] 0} <nil>
--- PASS: TestEtcdClientInit (0.08s)
PASS
可以看到 clientv3 與 etcd Server 的節(jié)點 localhost:2379 成功建立了連接,并且輸出了集群的信息,下面我們就可以對 etcd 進行操作了。
client 定義
接著我們來看一下 client 的定義:
type Client struct {
Cluster
KV
Lease
Watcher
Auth
Maintenance
// Username is a user name for authentication.
Username string
// Password is a password for authentication.
Password string
}
注意,這里顯示的都是可導出的模塊結構字段,代表了客戶端能夠使用的幾大核心模塊,其具體功能介紹如下:
- Cluster:向集群里增加 etcd 服務端節(jié)點之類,屬于管理員操作。
- KV:我們主要使用的功能,即操作 K-V。
- Lease:租約相關操作,比如申請一個 TTL=10 秒的租約。
- Watcher:觀察訂閱,從而監(jiān)聽最新的數(shù)據(jù)變化。
- Auth:管理 etcd 的用戶和權限,屬于管理員操作。
- Maintenance:維護 etcd,比如主動遷移 etcd 的 leader 節(jié)點,屬于管理員操作
以上就是etcd通信接口之客戶端API核心方法實戰(zhàn)的詳細內容,更多關于etcd通信接口客戶端API的資料請關注腳本之家其它相關文章!

