连接池实现

简介

实现机制

基于swoole channel实现,channel大小默认为10,每次获取连接时判断如果连接池为空,则新建连接,并在结束时放回channel中,放回时注意如果大于channel则销毁该连接,同理如果获取连接时小于5,也需要新建连接。只有 满足pool >=5 才从channel中获取该连接。放回时 满足 pool < 10&。而且需要检查该连接是否断开

pkg/core/src/pool/poolfactory.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @param string $name
* @param string $option
* @return mixed
*/
public function getPool(string $name,$option = "")
{
$channelName = $option.$name;
//检查当前进程 全局静态池里 是否存在该连接池
if(!isset($this->pools[$channelName]) || $this->pools[$channelName] === null){
$this->pools[$channelName] = new Channel($this->maxActive);
}
//检查连接池里 可用连接是否小于最小连接,如果小于则走新建逻辑,最后在回归池里
if($this->pools[$channelName]->length() < $this->minActive){
return container()->get($name)->create($option);
}
//获取连接,pop一个连接
$connection = null;
if(!$this->pools[$channelName]->isEmpty()){
$connection = $this->pools[$channelName]->pop();
}
//直接返回
if($connection !== null){
return $connection;
}
//channel is empty or not reach maxActive return new create
if($this->pools[$channelName]->length() < $this->maxActive){
return container()->get($name)->create($option);
}
$connection = $this->pools[$channelName]->pop($this->maxWaitTime);
if($connection === false){
CLog::error("channel pop timeout name:$name");
return container()->get($name)->create($option);
}
return $connection;
}