From ca802781d60625483f4093c751c958654c7f3bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Tue, 23 Nov 2021 11:58:13 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0etcd=E5=88=9D=E5=A7=8B?= =?UTF-8?q?=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/etcd/define.go | 26 +++++++++++++++++ middleware/etcd/init.go | 59 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 middleware/etcd/define.go create mode 100644 middleware/etcd/init.go diff --git a/middleware/etcd/define.go b/middleware/etcd/define.go new file mode 100644 index 0000000..2184c68 --- /dev/null +++ b/middleware/etcd/define.go @@ -0,0 +1,26 @@ +// Package etcd... +// +// Description : etcd... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-23 11:25 上午 +package etcd + +import ( + "math" + "time" +) + +const ( + // DefaultDialTimeout 默认超时时间 + DefaultDialTimeout = 5 * time.Second + // DefaultDialKeepAliveTime 默认ping时间 + DefaultDialKeepAliveTime = 3 * time.Second + // DefaultDialKeepAliveTimeout ping之后等待响应的超时时间, 超时未响应, 连接将会断开 + DefaultDialKeepAliveTimeout = 5 * time.Second + // DefaultMaxCallSendMsgSize 客户端请求体最大字节数, 默认 2M , 和etcd默认值保持一致 + DefaultMaxCallSendMsgSize = 2 * 1024 * 1024 + // DefaultMaxCallRecvMsgSize 客户端接受的响应题最大大小, 默认int32最大值, 和etcd默认值保持一致 + DefaultMaxCallRecvMsgSize = math.MaxInt32 +) diff --git a/middleware/etcd/init.go b/middleware/etcd/init.go new file mode 100644 index 0000000..8b53f61 --- /dev/null +++ b/middleware/etcd/init.go @@ -0,0 +1,59 @@ +// Package etcd ... +// +// Description : etcd ... +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 2021-11-23 10:53 上午 +package etcd + +import ( + "github.com/pkg/errors" + "go.etcd.io/etcd/clientv3" +) + +var ( + // Client 客户端 + Client *clientv3.Client +) + +// InitEtcdClient 初始化etcd连接 +// +// Author : go_developer@163.com<白茶清欢> +// +// Date : 10:53 上午 2021/11/23 +func InitEtcdClient(cfg clientv3.Config) error { + if nil == cfg.Endpoints || len(cfg.Endpoints) == 0 { + return errors.New("endpoints is empty") + } + + // 连接超时 + if cfg.DialTimeout == 0 { + cfg.DialTimeout = DefaultDialTimeout + } + + // ping 时间间隔 + if cfg.DialKeepAliveTime == 0 { + cfg.DialKeepAliveTime = DefaultDialKeepAliveTime + } + + // ping 响应超时时间 + if cfg.DialKeepAliveTimeout == 0 { + cfg.DialKeepAliveTimeout = DefaultDialKeepAliveTimeout + } + + // 客户端发送的最大请求体大小 + if cfg.MaxCallSendMsgSize <= 0 { + cfg.MaxCallSendMsgSize = DefaultMaxCallSendMsgSize + } + + // 客户端接受的最大响应体大小 + if cfg.MaxCallRecvMsgSize <= 0 { + cfg.MaxCallRecvMsgSize = DefaultMaxCallRecvMsgSize + } + var err error + if Client, err = clientv3.New(cfg); nil != err { + return errors.New("etcd连接失败 : " + err.Error()) + } + return nil +}