菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
2928
0

基于 swoole 协程的 MySQL 连接池

原创
05/13 14:22
阅读数 2520

连接池类

<?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();

测试结果

查看数据库连接数

发表评论

0/200
2928 点赞
0 评论
收藏
为你推荐 换一批