1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pool.go 1.85 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-08-20 23:24 . daemon
package client
import (
"fmt"
"github.com/apache/thrift/lib/go/thrift"
"sync"
)
var (
pool *Pool
)
type Pool struct {
sync.RWMutex
client map[string]*Client //有几个不同的机群,它们之间没有联系
factory map[string]thrift.TProtocolFactory
}
func newPool() *Pool {
if pool != nil {
return pool
}
pool = &Pool{
client: make(map[string]*Client, 0),
factory: make(map[string]thrift.TProtocolFactory, 0),
}
return pool
}
func NewClient(cfg Config) (*Client, error) {
p := newPool()
return p.newClient(cfg)
}
func (p *Pool) newClient(cfg Config) (*Client, error) {
p.Lock()
defer p.Unlock()
f, err := p.createFactory(cfg.Protocol)
if err != nil {
return nil, err
}
return p.createClient(f, cfg.Target)
}
func (p *Pool) createFactory(protocol string) (thrift.TProtocolFactory, error) {
if f, ok := p.factory[protocol]; ok {
return f, nil
}
f, err := newFactory(protocol)
if err != nil {
return nil, err
}
p.factory[protocol] = f
return f, nil
}
func (p *Pool) createClient(tpf thrift.TProtocolFactory, target string) (*Client, error) {
if cli, ok := p.client[target]; ok {
return cli, nil
}
cli, err := newClient(tpf, target)
if err != nil {
return nil, err
}
p.client[target] = cli
return cli, nil
}
func newFactory(protocol string) (thrift.TProtocolFactory, error) {
var factory thrift.TProtocolFactory
var err error
switch protocol {
case "compact":
factory = thrift.NewTCompactProtocolFactoryConf(&thrift.TConfiguration{})
break
case "simple_json":
factory = thrift.NewTCompactProtocolFactoryConf(&thrift.TConfiguration{})
break
case "json":
factory = thrift.NewTJSONProtocolFactory()
break
case "binary", "":
factory = thrift.NewTBinaryProtocolFactoryConf(&thrift.TConfiguration{})
break
default:
err = fmt.Errorf("NOT support %v protocol factory", protocol)
}
return factory, err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.6.1

搜索帮助

A270a887 8829481 3d7a4017 8829481