1.1 运行环境
- Golang版本: go1.14.3 darwin/amd64
- Thrift Golang库版本: 0.13.0
- Thrift IDL编辑器版本: 0.13.0
1.2 .thrift文件
namespace java com.czl.api.thrift.model
namespace cpp com.czl.api
namespace php com.czl.api
namespace py com.czl.api
namespace js com.czl.apixianz
namespace go com.czl.api
struct ApiRequest {
1: required i16 id;
}
struct ApiResponse{
1:required string name;
}
// service1
service ApiService1{
ApiResponse query(1:ApiRequest request)
}
// service2
service ApiService2{
ApiResponse query(1:ApiRequest request)
}
注:请通过安装Thrift IDL编译器,并生成客户端、服务端代码。
1.3 对照实验说明
通过脚本开启100个协程并发调用rpc服务10分钟,统计这段时间内,未使用thrift客户端连接池与使用客户端连接池服务的平均吞吐量、Thrift API调用平均延迟、机器端口消耗等数据进行性能对比。
- 实验一: 未使用thrift客户端连接池
- 实验二: 使用thrift客户端连接池
2 Thrift客户端连接池实现
2.1 连接池的功能
首先,我们要明确一下连接池的职责,这里我简单的总结一下,连接池主要功能是维护连接的创建、释放,通过缓存连接来复用连接,减少创建连接所带来的开销,提高系统的吞吐量,一般连接池还会有连接断开的重连机制、超时机制等。这里我们可以先定义出大部分连接池都会有的功能,只是定义,可以先不管每个功能的具体实现。每一个空闲Thrift客户端其实底层都维护着一条空闲TCP连接,空闲Thrift客户端与空闲连接在这里其实是同一个概念。
......
// Thrift客户端创建方法,留给业务去实现
type ThriftDial func(addr string, connTimeout time.Duration) (\*IdleClient, error)
// 关闭Thrift客户端,留给业务实现
type ThriftClientClose func(c \*IdleClient) error
// Thrift客户端连接池
type ThriftPool struct {
// Thrift客户端创建逻辑,业务自己实现
Dial ThriftDial
// Thrift客户端关闭逻辑,业务自己实现
Close ThriftClientClose
// 空闲客户端,用双端队列存储
idle list.List
// 同步锁,确保count、status、idle等公共数据并发操作安全
lock \*sync.Mutex
// 记录当前已经创建的Thrift客户端,确保MaxConn配置
count int32
// Thrift客户端连接池状态,目前就open和stop两种
status uint32
// Thrift客户端连接池相关配置
config \*ThriftPoolConfig
}
// 连接池配置
type ThriftPoolConfig struct {
// Thrfit Server端地址
Addr string
// 最大连接数
MaxConn int32
// 创建连接超时时间
ConnTimeout time.Duration
// 空闲客户端超时时间,超时主动释放连接,关闭客户端
IdleTimeout time.Duration
// 获取Thrift客户端超时时间
Timeout time.Duration
// 获取Thrift客户端失败重试间隔
interval time.Duration
}
// Thrift客户端
type IdleClient struct {
// Thrift传输层,封装了底层连接建立、维护、关闭、数据读写等细节
Transport thrift.TTransport
// 真正的Thrift客户端,业务创建传入
RawClient interface{
}
}
// 封装了Thrift客户端
type idleConn struct {
// 空闲Thrift客户端
c \*IdleClient
// 最近一次放入空闲队列的时间
t time.Time
}
// 获取Thrift空闲客户端
func (p \*ThriftPool) Get() (\*IdleClient, error) {
// 1. 从空闲池中获取空闲客户端,获取到更新数据,返回,否则执行第2步
// 2. 创建新到Thrift客户端,更新数据,返回Thrift客户端
......
}
// 归还Thrift客户端
func (p \*ThriftPool) Put(client \*IdleCLient) error {
// 1. 如果客户端已经断开,更新数据,返回,否则执行第2步
// 2. 将Thrift客户端丢进空闲连接池,更新数据,返回
......
}
// 超时管理,定期释放空闲太久的连接
func (p \*ThriftPool) CheckTimeout() {
// 扫描空闲连接池,将空闲太久的连接主动释放掉,并更新数据
......
}
// 异常连接重连
func (p \*ThriftPool) Reconnect(client \*IdleClient) (newClient \*IdleClient, err error) {
// 1. 关闭旧客户端
// 2. 创建新的客户端,并返回
......
}
// 其他方法
......
这里有两个关键的数据结构,ThriftPool和IdleClient,ThriftPool负责实现整个连接池的功能,IdleClient封装了真正的Thrift客户端。先看一下ThriftPool的定义:
// Thrift客户端创建方法,留给业务去实现
type ThriftDial func(addr string, connTimeout time.Duration) (\*IdleClient, error)