目录前言etcd clientv3 客户端etcd 客户端初始化client 定义前言 我们在前面介绍了 etcd 的整体架构。学习客户端与 etcd 服务端的通信以及 etcd 集
我们在前面介绍了 etcd 的整体架构。学习客户端与 etcd 服务端的通信以及 etcd 集群节点的内部通信接口对于我们更好地使用和掌握 etcd 组件很有帮助,也是所必需了解的内容。我们将会介绍 etcd 的 grpc 通信接口以及客户端的实践。
etcd 客户端 clientv3 接入的示例将会以 Go 客户端为主,读者需要准备好基本的开发环境。
首先是 etcd clientv3 的初始化,我们根据指定的 etcd 节点,建立客户端与 etcd 集群的连接。
cli,err := clientv3.New(clientv3.Config{
Endpoints:[]string{"localhost:2379"},
DialTimeout: 5 * time.Second,
})
如上的代码实例化了一个 client,这里需要传入的两个参数:
解决完包依赖之后,我们初始化 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{
// 节点配置
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()
}
如上的代码,预期的执行结果如下:
=== 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 的节点 localhost:2379 成功建立了连接,并且输出了集群的信息,下面我们就可以对 etcd 进行操作了。
接着我们来看一下 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
}
注意,这里显示的都是可导出的模块结构字段,代表了客户端能够使用的几大核心模块,其具体功能介绍如下:
以上就是etcd通信接口之客户端api核心方法实战的详细内容,更多关于etcd通信接口客户端API的资料请关注编程网其它相关文章!
--结束END--
本文标题: etcd通信接口之客户端API核心方法实战
本文链接: https://www.lsjlt.com/news/151847.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
2024-04-05
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0