PDO Connection Pool

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


Latest version: pecl install openswoole-22.1.2

This is a PDO 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 PDOPool to manage a pool of connection to database servers or remote services.

Methods

PDO Connection Pool Config

Example

declare(strict_types=1);

use Swoole\Database\PDOConfig;
use Swoole\Database\PDOPool;
use Swoole\Runtime;

const N = 5;

Runtime::enableCoroutine();
$s = microtime(true);
Co\run(function () {
    $pool = new PDOPool(
        (new PDOConfig())
            ->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) {
            $pdo = $pool->get();
            $statement = $pdo->prepare('SELECT ? + ?');
            if (!$statement) {
                throw new RuntimeException('Prepare failed');
            }
            $a = mt_rand(1, 100);
            $b = mt_rand(1, 100);
            $result = $statement->execute([$a, $b]);
            if (!$result) {
                throw new RuntimeException('Execute failed');
            }
            $result = $statement->fetchAll();
            if ($a + $b !== (int) $result[0][0]) {
                throw new RuntimeException('Bad result');
            }
            $pool->put($pdo);
        });
    }
});
Last updated on August 31, 2022