基于 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 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!