增加etcd初始化

This commit is contained in:
白茶清欢 2021-11-23 11:58:13 +08:00
parent 154962fb73
commit ca802781d6
2 changed files with 85 additions and 0 deletions

26
middleware/etcd/define.go Normal file
View File

@ -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
)

59
middleware/etcd/init.go Normal file
View File

@ -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
}