通过swoole的chan实现简易的连接池基类,有需要的小伙伴可以参考一下。
<?php
abstract class Pool
{
/**
* 客户端使用管道存储
* @var \chan
*/
private $clients;
/**
* 最大值
* @var int
*/
protected $size = 200;
/**
* 缺省值
* @var int
*/
protected $defaultSize = 10;
/**
* 超时时间
* @var int
*/
protected $timeout = 3;
/**
* 检测时间
* @var float|int
*/
protected $intervalMs = 15 * 1000;
/**
* 是否开启自动检测
* @var bool
*/
protected $autoCheck = false;
protected function __construct()
{
$this->clients = new \chan($this->size);
// 自动检测
if($this->autoCheck){
swoole_timer_tick($this->intervalMs,function (){
while ($this->clients->length() > $this->defaultSize){
$client = $this->clients->pop($this->timeout);
$this->disconnect($client);
}
});
}
}
/**
* 获取客户端
* @return mixed
*/
final public function get()
{
$client = $this->clients->pop($this->timeout);
if (empty($client)) {
$client = $this->getClient();
}
if ($this->check($client) == false) {
$client = $this->getClient();
}
defer(function () use ($client) {
$this->push($client);
});
return $client;
}
/**
* 入栈
* @param $client
* @return bool
*/
final protected function push($client)
{
if ($this->clients->isFull()) {
$this->disconnect($client);
return false;
}
$this->clients->push($client);
return true;
}
/**
* 获取客户端
* @return mixed
*/
final protected function getClient()
{
$client = $this->connect();
$this->push($client);
return $client;
}
abstract protected function check($client): bool;
abstract protected function disconnect($client);
abstract protected function connect();
}