用户可以根据自己的业务场景来选择短连接、长连接池、连接多路复用。Kitex 自 v0.0.2 版本默认配置了连接池,但建议用户还是根据实际情况调整连接池的大小。
每次请求都会创建一次连接,性能不佳,通常不建议使用。但部分场景必须使用短连接,如上游实例数过多时,会增加下游服务的负担,请根据情况来选择。
配置短连接:
xxxCli := xxxservice.NewClient("destServiceName", client.WithShortConnection())
Kitex >= v0.0.2 默认配置了连接池,配置参数如下:
connpool2.IdleConfig{
MaxIdlePerAddress: 10,
MaxIdleGlobal: 100,
MaxIdleTimeout: time.Minute,
MinIdlePerAddress: 2,
}
建议用户根据实际情况调整连接池大小,配置方式如下:
xxxCli := xxxservice.NewClient("destServiceName", client.WithLongConnection(connpool.IdleConfig{10, 1000, time.Minute}))
其中:
MaxIdlePerAddress
表示每个后端实例可允许的最大闲置连接数MaxIdleGlobal
表示全局最大闲置连接数MaxIdleTimeout
表示连接的闲置时长,超过这个时长的连接会被关闭(最小值 3s,默认值 30s )MinIdlePerAddress
(Kitex >= v0.4.3)MaxIdleTimeout
也不会被清理。MinIdlePerAddress
的值不能超过5。长连接池的实现方案是每个 address 对应一个连接池,这个连接池是一个由连接构成的 ring,ring 的大小为 MaxIdlePerAddress。
当选择好目标地址并需要获取一个连接时,按以下步骤处理 :
在连接使用完毕准备归还时,按以下步骤依次处理:
下面是参数设置的一些建议:
MaxIdlePerAddress
表示池化的连接数量,最小为 1,否则长连接会退化为短连接MaxIdlePerAddress = qps_per_dest_host*avg_response_time_sec
MinIdlePerAddress
MaxIdleGlobal
表示总的空闲连接数应大于 下游目标总数*MaxIdlePerAddress
,超出部分是为了限制未能从连接池中获取连接而主动新建连接的总数量MaxIdleTimeout
表示连接空闲时间,由于 server 在 10min 内会清理不活跃的连接,因此 client 端也需要及时清理空闲较久的连接,避免使用无效的连接,该值在下游也为 Kitex 时不可超过 10min开启连接多路复用,Client 访问 Server 常规只需要1个连接即可,相比连接池极限测试吞吐表现更好(目前的极限测试配置了2个连接),且能大大减少连接数量。
特别说明:
Server 配置
option: WithMuxTransport
svr := xxxservice.NewServer(handler, server.WithMuxTransport())
Client 配置
option: WithMuxConnection
建议配置1-2 个连接
xxxCli := NewClient("destServiceName", client.WithMuxConnection(1))
连接池定义了 Reporter
接口,用于连接池状态监控,例如长连接的复用率。
如有需求,用户需要自行实现该接口,并通过 SetReporter
注入。
// Reporter report status of connection pool.
type Reporter interface {
ConnSucceed(poolType ConnectionPoolType, serviceName string, addr net.Addr)
ConnFailed(poolType ConnectionPoolType, serviceName string, addr net.Addr)
ReuseSucceed(poolType ConnectionPoolType, serviceName string, addr net.Addr)
}
// SetReporter set the common reporter of connection pool, that can only be set once.
func SetReporter(r Reporter)