原文地址:etcd/clientv3
etcd/clientv3
是v3版本的Go etcd官方客戶端
安裝
go get go.etcd.io/etcd/clientv3
開始
創建客戶端使用clientv3.New
:
cli, err := clientv3.New(clientv3.Config{
Endpoints: []string{"localhost:2379", "localhost:22379", "localhost:32379"},
DialTimeout: 5 * time.Second,
})
if err != nil {
// handle error!
}
defer cli.Close()
etcd v3使用gRPC
進行遠程程序調用,並且clientv3
使用grpc-go
連接etcd。確保在使用完客戶端后關閉它,如果客戶端沒有關閉,連接將會有泄漏的goroutines
。指定超時時間,通過context.WithTimeout
使用APIs:
ctx, cancel := context.WithTimeout(context.Background(), timeout)
resp, err := cli.Put(ctx, "sample_key", "sample_value")
cancel()
if err != nil {
// handle error!
}
// use the response
為了完全兼容,建議使用etcd's中的vendored包進行構建,使用工具像golang/dep
,在vendor目錄內。
錯誤處理
etcd客戶端返回兩種類型的錯誤:
- context error :canceled or deadline exceeded.
- gRpc error : 看api/v3rpc/rpctypes.
這里有例子處理客戶端錯誤:
resp, err := cli.Put(ctx, "", "")
if err != nil {
switch err {
case context.Canceled:
log.Fatalf("ctx is canceled by another routine: %v", err)
case context.DeadlineExceeded:
log.Fatalf("ctx is attached with a deadline is exceeded: %v", err)
case rpctypes.ErrEmptyKey:
log.Fatalf("client-side error: %v", err)
default:
log.Fatalf("bad cluster endpoints, which are not etcd servers: %v", err)
}
}
監控
etcd客戶端可以通過go-grpc-prometheus,選擇RPC監控指標,看例子。
命名空間
namespace包提供clientv3
接口封裝透明隔離客戶端請求到用戶定義的前綴。
請求大小限制
客戶端請求大小限制通過clientv3.Config.MaxCallSendMsgSize
和MaxCallRecvMsgSize
進行配置。如果沒有給予值,客戶端請求發送限制包括gRPC負載默認2MB。接收限制默認為math.MaxInt32
。
例子
更多代碼例子可以從GoDoc發現。