EasySwoole Pool 数据库连接池

EasySwoole Pool连接池可用于Redis、MySQL等数据库连接。

SwooleMySQL是我在Swoole官方MySQL类的基础上封装的一个类,可以实现类似ThinkPHP里db()函数和模型的链式操作,现我要为他创建一个连接池。

1. 首先安装composer依赖

composer require easyswoole/pool

2. 定义池对象

App目录下新建Pool目录,并新建SwooleMySQLPool.php类,内容如下

<?php

namespace App\Pool;

use EasySwoole\Pool\Config;
use EasySwoole\Pool\AbstractPool;
use App\Services\SwooleMySQL;

class SwooleMySQLPool extends AbstractPool
{

    /**
     * SwooleMySQLPool constructor.
     * @param Config      $conf
     * @throws \EasySwoole\Pool\Exception\Exception
     */
    public function __construct(Config $conf)
    {
        parent::__construct($conf);
    }

    protected function createObject()
    {
        $mysql = new SwooleMySQL();
        return $mysql;
    }
}

3. 注册连接池

EasySwooleEvent.php中加入以下代码

//SwooleMySQL连接池
$config2 = new \EasySwoole\Pool\Config();
$config2->setMinObjectNum(10);
$config2->setMaxObjectNum(100);
$config2->setIntervalCheckTime(10 * 1000);
\EasySwoole\Pool\Manager::getInstance()->register(new \App\Pool\SwooleMySQLPool($config2),'swoole_mysql_pool');

4. 在控制器中使用连接池

public function test_mysql_pool(){
    go(function (){
        $mysql_pool = \EasySwoole\Pool\Manager::getInstance()->get('swoole_mysql_pool');
        $mysql1 = $mysql_pool->getObj();
        $mysql2 = $mysql_pool->getObj();

        var_dump($mysql_pool->status());

        $result1 = $mysql1->table('user_coin')->where(['user_id' => 18498, 'coin' => 'usdt'])->find();
        var_dump($result1);

        $result1 = $mysql2->table('user_coin')->where(['user_id' => 18499, 'coin' => 'usdt'])->find();
        var_dump($result1);

        //回收对象
        $mysql_pool->recycleObj($mysql1);
        $mysql_pool->recycleObj($mysql2);

        var_dump($mysql_pool->status());
    });
}

至此SwooleMySQL连接池的创建和使用完毕,有了这个连接池,就不用显式的调用$mysql->close()方法了,只需用完之后回收,方便不少。

Leave a Comment

豫ICP备19001387号-1