swoole 连接池

declare(strict_types=1);

//引入
use Swoole\Coroutine;
use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;


protected $pool = null;
public function __construct(){
//配置链接池
//创建WebSocket Server对象,监听0.0.0.0:9307端口。
        $ws = new \Swoole\WebSocket\Server('0.0.0.0', 9308);
        $this->pool = new PDOPool((new PDOConfig)
            ->withHost('***’)
            ->withPort(3306)
            // ->withUnixSocket('/tmp/mysql.sock')
            ->withDbName('***')
            ->withCharset('utf8mb4')
            ->withUsername('***')
            ->withPassword('***')
        );
}



//执行sql语句
    public function pdo($sql = '', $type = 'find')
    {
        $pdo = $this->pool->get();
        if ($type == 'select') {
            $type = 'fetchAll';
        } elseif ($type == 'find') {
            $type = 'fetch';
        } else {
            $res = $pdo->prepare($sql)->execute();
        }
        switch ($type) {
            case 'fetchAll':
                $res = $pdo->query($sql)->fetchAll();
                break;
            case 'fetch':
                $res = $pdo->query($sql)->fetch();
                break;
        }
        $this->pool->put($pdo);
        if ($res) {
            return $res;
        }
        return false;
    }

 

posted @ 2024-08-21 14:17  祈愿仙帝  阅读(1)  评论(0编辑  收藏  举报