ETCD:客户端v3

原文地址: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客户端返回两种类型的错误:

  1. context error :canceled or deadline exceeded.
  2. 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.MaxCallSendMsgSizeMaxCallRecvMsgSize进行配置。如果没有给予值,客户端请求发送限制包括gRPC负载默认2MB。接收限制默认为math.MaxInt32

例子

更多代码例子可以从GoDoc发现。

猜你喜欢

转载自www.cnblogs.com/cbkj-xd/p/11938273.html