MySQLi Connection Pool

4.x is outdated, please check the latest version 22.x


Latest version: pecl install openswoole-22.1.2

This is a MySQLi implementaion of ConnectionPool.

Connection pool is used to reduce the TCP reconnect overhead, can be used to increase the application performance.

You can use the build-in MysqliPool to manage a pool of connection to database servers or remote services.

Methods

PDO Connection Pool Config

Example

<?php

declare(strict_types=1);

use Swoole\Database\MysqliConfig;
use Swoole\Database\MysqliPool;
use Swoole\Runtime;

const N = 5;

Runtime::enableCoroutine();
Co\run(function () {
    $pool = new MysqliPool(
        (new MysqliConfig())
            ->withHost(MYSQL_SERVER_HOST)
            ->withPort(MYSQL_SERVER_PORT)
            // ->withUnixSocket('/tmp/mysql.sock')
            ->withDbName(MYSQL_SERVER_DB)
            ->withCharset('utf8mb4')
            ->withUsername(MYSQL_SERVER_USER)
            ->withPassword(MYSQL_SERVER_PWD)
    );
    for ($n = N; $n--;) {
        go(function () use ($pool) {
            $mysqli = $pool->get();
            $statement = $mysqli->prepare('SELECT ? + ?');
            if (!$statement) {
                throw new RuntimeException('Prepare failed');
            }
            $a = mt_rand(1, 100);
            $b = mt_rand(1, 100);
            if (!$statement->bind_param('dd', $a, $b)) {
                throw new RuntimeException('Bind param failed');
            }
            if (!$statement->execute()) {
                throw new RuntimeException('Execute failed');
            }
            if (!$statement->bind_result($result)) {
                throw new RuntimeException('Bind result failed');
            }
            if (!$statement->fetch()) {
                throw new RuntimeException('Fetch failed');
            }
            if ($a + $b !== (int) $result) {
                throw new RuntimeException('Bad result');
            }
            while ($statement->fetch()) {
                continue;
            }
            $pool->put($mysqli);
        });
    }
});
Last updated on August 31, 2022