PHP code example of allsilaevex / swoole-connection-pool

1. Go to this page and download the library: Download allsilaevex/swoole-connection-pool library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

allsilaevex / swoole-connection-pool example snippets




declare(strict_types=1);

nction () {
    $connectionPoolFactory = \Allsilaevex\ConnectionPool\ConnectionPoolFactory::create(
        size: 2,
        factory: new \Allsilaevex\ConnectionPool\ConnectionFactories\PDOConnectionFactory(
            dsn: 'mysql:host=0.0.0.0;port=3306;dbname=default',
            username: 'root',
            password: 'root',
        ),
    );

    $pool = $connectionPoolFactory->instantiate();

    \Swoole\Coroutine\parallel(n: 4, fn: static function () use ($pool) {
        /** @var \PDO $connection */
        $connection = $pool->borrow();

        $result = $connection->query('select 42')->fetchColumn();

        var_dump($result);
    });
});



declare(strict_types=1);

\Swoole\Coroutine\run(static function () {
    \Swoole\Coroutine\go(static function () {
        echo '1' . PHP_EOL;

        $pdo = new \PDO(
            dsn: 'mysql:host=0.0.0.0;port=3306;dbname=default',
            username: 'root',
            password: 'root',
        );

        echo '2' . PHP_EOL;

        $pdo->query('select 1')->fetchAll();

        echo '4' . PHP_EOL;
    });

    \Swoole\Coroutine\go(static function () {
        echo '3' . PHP_EOL;
    });
});

// output:
// 1
// 3
// 2
// 4



declare(strict_types=1);

nction () {
    $connectionPoolFactory = \Allsilaevex\ConnectionPool\ConnectionPoolFactory::create(
        // Maximum number of connections in the pool
        size: 4,

        // A trivial PDO connection factory
        // For other connections, you need to define factory that implements \Allsilaevex\Pool\PoolItemFactoryInterface
        factory: new \Allsilaevex\ConnectionPool\ConnectionFactories\PDOConnectionFactory(
            dsn: 'mysql:host=0.0.0.0;port=3306;dbname=default',
            username: 'root',
            password: 'root',
        ),
    );

    // The minimum number of connections that the pool will maintain
    // Setting it to 0 means the pool will create connections only when needed
    // Setting it to MAX means the pool will always keep exactly MAX connections
    $connectionPoolFactory->setMinimumIdle(2);

    // The time during which connections can remain idle in the pool
    // After the timeout expires, connections will be destroyed until the pool size reaches the minimumIdle value
    $connectionPoolFactory->setIdleTimeoutSec(15.0);

    // Maximum connection lifetime
    // When setting this, it's recommended to consider database limits and infrastructure constraints.
    $connectionPoolFactory->setMaxLifetimeSec(60.0);

    // Maximum waiting time for reserving a connection for re-creation (see maxLifetimeSec)
    // This can be useful when all connections in the pool are constantly occupied for a long time
    // Setting it to .0 means there will be no waiting during reservation
    $connectionPoolFactory->setMaxItemReservingForUpdateWaitingTimeSec(.5);

    // The maximum waiting time for a connection from the pool during a borrow attempt
    // After this time expires, an \Allsilaevex\Pool\Exceptions\BorrowTimeoutException will be thrown
    $connectionPoolFactory->setBorrowingTimeoutSec(.1);

    // The maximum waiting time for returning a connection to the pool
    // After this time expires, the connection will be destroyed
    $connectionPoolFactory->setReturningTimeoutSec(.01);

    // If true, then connection will automatically return to the pool after the coroutine in which it was borrowed finishes execution
    // Auto return can only work with coroutine binding!
    $connectionPoolFactory->setAutoReturn(true);

    // If true, then when borrowing a connection from the pool for one coroutine, the same connection will always be returned
    $connectionPoolFactory->setBindToCoroutine(true);

    // A logger is used to signal abnormal situations
    // Any logger that implements \Psr\Log\LoggerInterface is allowed
    $connectionPoolFactory->setLogger(logger: new \Psr\Log\NullLogger());

    // Maximum time that a connection can be out of the pool without leak warnings
    $connectionPoolFactory->setLeakDetectionThresholdSec(1.0);

    // Allows adding a KeepaliveChecker that must implement the \Allsilaevex\ConnectionPool\KeepaliveCheckerInterface
    // This checker will be called at a specified interval and can trigger connection re-creation (if it returns false)
    $connectionPoolFactory->addKeepaliveChecker(
        new class () implements \Allsilaevex\ConnectionPool\KeepaliveCheckerInterface {
            public function check(mixed $connection): bool
            {
                try {
                    $connection->getAttribute(\PDO::ATTR_SERVER_INFO);
                } catch (\Throwable) {
                    return false;
                }

                return true;
            }

            public function getIntervalSec(): float
            {
                return 60.0;
            }
        },
    );

    // Allows adding a ConnectionChecker that must be callable
    // This checker will be called before connection borrowing and can trigger connection re-creation (if it returns false)
    $connectionPoolFactory->addConnectionChecker(
        static function (\PDO $connection): bool {
            try {
                return !$connection->inTransaction();
            } catch (\Throwable) {
                return false;
            }
        },
    );

    // You can specify a pool name for identifying logs, metrics, etc.
    // Or leave the field empty and the name will be generated based on the factory class
    $pool = $connectionPoolFactory->instantiate(name: 'my-pool');

    \Swoole\Coroutine\parallel(n: 8, fn: static function () use ($pool) {
        /** @var \PDO $connection */
        $connection = $pool->borrow();

        $result = $connection->query('select 42')->fetchColumn();

        var_dump($result);
    });
});