基于 swoole 协程的 MySQL 连接池
连接池类
<?php
// +----------------------------------------------------------------------
// | Created by PhpStorm
// +----------------------------------------------------------------------
// | Date: 19-1-4 上午9:42
// +----------------------------------------------------------------------
// | Author: woann <304550409@qq.com>
// +----------------------------------------------------------------------
class MysqlPool{
private $pool; //连接池容器
public static $instance = null; //实例
private $config = [
'max_num' => 100,
'mysql' =>[
'host' => '127.0.0.1',
'port' => 3306,
'user' => 'user',
'password' => 'password',
'database' => 'dbname',
]
];
//防止手欠在外部实例化,将构造函数私有化
private function __construct()
{
}
/**
* @author woann<304550409@qq.com>
* @des 初始化
*/
function init()
{
$this->pool = new chan($this->config["max_num"]);//用channel来作为连接池容器
for ($i = 0; $i < $this->config["max_num"]; $i++) {
$mysql = new Swoole\Coroutine\MySQL();
$res = $mysql->connect($this->config['mysql']);
if ($res == false) {
throw new RuntimeException("failed to connect mysql server");
}
$this->release($mysql);
}
}
/**
* @author woann<304550409@qq.com>
* @return MysqlPool|null
* @des 获取连接池实例
*/
static public function getInstance()
{
if (self::$instance == null) {
$mysqlpool = new MysqlPool();
$mysqlpool->init();
self::$instance = $mysqlpool;
}
return self::$instance;
}
/**
* @author woann<304550409@qq.com>
* @return mixed
* @des 获取链接
*/
function get()
{
return $this->pool->pop();
}
/**
* @author woann<304550409@qq.com>
* @param $mysql
* @des 回收链接
*/
function release($mysql)
{
$this->pool->push($mysql);
}
}
测试
用swoole的httpserver进行测试
<?php
// +----------------------------------------------------------------------
// | Created by PhpStorm
// +----------------------------------------------------------------------
// | Date: 19-1-4 上午9:58
// +----------------------------------------------------------------------
// | Author: woann <304550409@qq.com>
// +----------------------------------------------------------------------
require_once "MysqlPool.php";//引入连接池类
$server = new Swoole\Http\Server("127.0.0.1", 9501);//创建httpserver
$server->set([
'worker_num' => 1,
]);
$server->on('Request', function($request, $response) {
$pool = MysqlPool::getInstance();//获取连接池实例
$conn = $pool->get();//获取链接
$stmt = $conn->prepare('SELECT * FROM usertb WHERE id = ?'); //预处理
if ($stmt == false) {
var_dump($conn->errno, $conn->error);
}
$res = $stmt->execute(array(9988));//绑定参数 执行sql
$pool->release($conn);//释放回收链接
$response->end(json_encode($res));//将查询结果转成json格式输出到浏览器
});
$server->start();
测试结果
查看数据库连接数
本作品采用《CC 协议》,转载必须注明作者和本文链接