PDO Connection Pool

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

  • Swoole\Database\PDOPool->__construct
  • Swoole\Database\PDOPool->make
  • Swoole\Database\PDOPool->fill
  • Swoole\Database\PDOPool->get
  • Swoole\Database\PDOPool->put
  • Swoole\Database\PDOPool->close

    PDO Connection Pool Config

  • Swoole\Database\PDOConfig

    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);
            });
        }
    });