优化etcd Client

This commit is contained in:
白茶清欢 2023-08-15 12:46:58 +08:00
parent 6beadd85f7
commit fcf2830889

54
init.go
View File

@ -10,19 +10,33 @@ package etcd
import ( import (
"errors" "errors"
"go.etcd.io/etcd/clientv3" "go.etcd.io/etcd/clientv3"
"sync"
) )
var ( var (
// Client 客户端 // Client 客户端
Client *clientv3.Client Client *client
) )
// InitEtcdClient 初始化etcd连接 func init() {
Client = &client{
table: make(map[string]*clientv3.Client),
lock: &sync.RWMutex{},
}
}
type client struct {
// table 实例表
table map[string]*clientv3.Client
lock *sync.RWMutex
}
// AddEtcdClient 初始化etcd连接
// //
// Author : go_developer@163.com<白茶清欢> // Author : go_developer@163.com<白茶清欢>
// //
// Date : 10:53 上午 2021/11/23 // Date : 10:53 上午 2021/11/23
func InitEtcdClient(cfg clientv3.Config) error { func (c *client) AddEtcdClient(flag string, cfg clientv3.Config) error {
if nil == cfg.Endpoints || len(cfg.Endpoints) == 0 { if nil == cfg.Endpoints || len(cfg.Endpoints) == 0 {
return errors.New("endpoints is empty") return errors.New("endpoints is empty")
} }
@ -51,9 +65,39 @@ func InitEtcdClient(cfg clientv3.Config) error {
if cfg.MaxCallRecvMsgSize <= 0 { if cfg.MaxCallRecvMsgSize <= 0 {
cfg.MaxCallRecvMsgSize = DefaultMaxCallRecvMsgSize cfg.MaxCallRecvMsgSize = DefaultMaxCallRecvMsgSize
} }
var err error var (
if Client, err = clientv3.New(cfg); nil != err { flagClient *clientv3.Client
err error
)
if flagClient, err = clientv3.New(cfg); nil != err {
return errors.New("etcd连接失败 : " + err.Error()) return errors.New("etcd连接失败 : " + err.Error())
} }
c.lock.Lock()
defer c.lock.Unlock()
c.table[flag] = flagClient
return nil return nil
} }
// GetClient ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:44 2023/8/15
func (c *client) GetClient(flag string) *clientv3.Client {
flagClient, _ := c.GetClientWithError(flag)
return flagClient
}
// GetClientWithError ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 12:44 2023/8/15
func (c *client) GetClientWithError(flag string) (*clientv3.Client, error) {
c.lock.RLock()
defer c.lock.RUnlock()
if _, exist := c.table[flag]; !exist {
return nil, errors.New(flag + " client instance not found")
}
return c.table[flag], nil
}