swoole 简单实现mysql数据库连接池
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2020/4/4
* Time: 21:26
*/
namespace app\api\driver;
use http\Exception\RuntimeException;
class Pool
{
protected $poolSize;//最大连接数
protected $pool;//存储链接对象
private $config;
private $mysql;
private static $instance;
//单例模式 三私一共
private function __construct($config)
{
if(empty($this->pool)){
echo "协程对象创建\n";
$this->config = $config;
//通过协程创建mysql对象
Co\run(function () use($config){//创建协程容器
$this->pool = new chan($config['pool_size']);
for ($i=0;$i<$config['pool_size'];$i++){
//创建线程
go(function () use($config){
$mysql = new Swoole\Coroutine\MySQL();
$res = $mysql->connent($config);
if($res === false){
throw new RuntimeException('Failed to mysql connet server');
}else{
//进入通道
$this->pool->push($mysql,$this->config['timeout']);
}
});
}
});
}else{
echo "对象创建失败\n";
}
}
public static function getInstance(array $congig = null){
echo "开始创建对象\n";
if(empty(self::$instance)){
if(empty($congig)){
echo "配置不能为空\n";
throw new RuntimeException('mysql confing is null');
}
self::$instance = new self($congig);
echo "对象创建成功并返回\n";
}
return self::$instance;
}
public function get(){
go(function (){
var_dump($this->pool->length());
if($this->pool->length() > 0){
$this->mysql = $this->pool->pop($this->config['pool_get_timeout']);
if($this->mysql === false){
throw new RuntimeException('mysql timeout');
}
//
defer(function (){
$this->pool->push($this->mysql);
});
}else{
throw new RuntimeException('pool length <= 0');
}
});
return $this->mysql;
}
private function __clone()
{
// TODO: Implement __clone() method.
}
}
$config = array(
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'root',
'password' => '',
'database' => 'hifuli',
'timeout' => -1,
); //mysql配置
echo "程序开始执行\n";
$mysqlpoll = Pool::getInstance($config);
$mysql = $mysqlpoll->get();
echo "程序结束\n";
var_dump($mysql);