基於 swoole 協程的 MySQL 連線池

woann發表於2019-01-05

連線池類

<?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 協議》,轉載必須註明作者和本文連結

相關文章