Join 4,000+ others and never miss out on new tips, tutorials, and more.
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.
Swoole\Database\MysqliPool->__construct
Swoole\Database\MysqliPool->make
Swoole\Database\MysqliPool->fill
Swoole\Database\MysqliPool->get
Swoole\Database\MysqliPool->put
Swoole\Database\MysqliPool->close
<?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);
});
}
});