Pool Connection Pool
Sharing a single connection among multiple coroutines can lead to data confusion, so a connection pool is needed to manage resources like databases and Redis connections.
Tip
This feature requires workerman>=5.1.0
Note
- The underlying system automatically supports Swoole/Swow/Fiber/Select/Event driven
- When using Fiber/Select/Event driven with blocking extensions like PDO Redis, it automatically degrades to a connection pool with only one connection
Redis Connection Pool
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Pool;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
class RedisPool
{
private Pool $pool;
public function __construct($host, $port, $max_connections = 10)
{
$this->pool = new Pool($max_connections);
// Set the method to create connections for the connection pool
$this->pool->setConnectionCreator(function () use ($host, $port) {
$redis = new \Redis();
$redis->connect($host, $port);
return $redis;
});
// Set the method to destroy connections for the connection pool
$this->pool->setConnectionCloser(function ($redis) {
$redis->close();
});
// Set the heartbeat check method
$this->pool->setHeartbeatChecker(function ($redis) {
$redis->ping();
});
}
// Get a connection
public function get(): \Redis
{
return $this->pool->get();
}
// Return a connection
public function put($redis): void
{
$this->pool->put($redis);
}
}
// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
static $pool;
if (!$pool) {
$pool = new RedisPool('127.0.0.1', 6379, 10);
}
$redis = $pool->get();
$redis->set('key', 'hello');
$value = $redis->get('key');
$pool->put($redis);
$connection->send($value);
};
Worker::runAll();
MySQL Connection Pool (supports automatic acquisition and return of connections)
<?php
use Workerman\Connection\TcpConnection;
use Workerman\Coroutine\Context;
use Workerman\Coroutine;
use Workerman\Coroutine\Pool;
use Workerman\Events\Swoole;
use Workerman\Protocols\Http\Request;
use Workerman\Worker;
require_once __DIR__ . '/vendor/autoload.php';
class Db
{
private static ?Pool $pool = null;
public static function __callStatic($name, $arguments)
{
if (self::$pool === null) {
self::initializePool();
}
// Retrieve the connection from the coroutine context to ensure the same coroutine uses the same connection
$pdo = Context::get('pdo');
if (!$pdo) {
// Get a connection from the connection pool
$pdo = self::$pool->get();
Context::set('pdo', $pdo);
// Automatically return the connection when the coroutine ends
Coroutine::defer(function () use ($pdo) {
self::$pool->put($pdo);
});
}
return call_user_func_array([$pdo, $name], $arguments);
}
private static function initializePool(): void
{
self::$pool = new Pool(10);
self::$pool->setConnectionCreator(function () {
return new \PDO('mysql:host=127.0.0.1;dbname=your_database', 'your_username', 'your_password');
});
self::$pool->setConnectionCloser(function ($pdo) {
$pdo = null;
});
self::$pool->setHeartbeatChecker(function ($pdo) {
$pdo->query('SELECT 1');
});
}
}
// Http Server
$worker = new Worker('http://0.0.0.0:8001');
$worker->eventLoop = Swoole::class; // Or Swow::class or Fiber::class
$worker->onMessage = function (TcpConnection $connection, Request $request) {
$value = Db::query('SELECT NOW() as now')->fetchAll();
$connection->send(json_encode($value));
};
Worker::runAll();
Interface Description
interface PoolInterface
{
/**
* Constructor
* @param int $max_connections Maximum number of connections, default is 1
* @param array $config = [
* 'min_connections' => 1, // Minimum number of connections, default is 1
* 'idle_timeout' => 60, // Connection idle timeout (seconds), default is 60 seconds, connections will be destroyed and removed from the pool after 60 seconds
* 'heartbeat_interval' => 50, // Heartbeat check interval (seconds), default is 50 seconds, checks if the connection is normal every 50 seconds
* 'wait_timeout' => 10, // Wait timeout (seconds) for getting connections, default is 10 seconds, an exception will be thrown if the connection fails to be retrieved after 10 seconds
* ]
*/
public function __construct(int $max_connections = 1, array $config = []);
/**
* Get a connection
*/
public function get(): mixed;
/**
* Return a connection
*/
public function put(object $connection): void;
/**
* Create a connection
*/
public function createConnection(): object;
/**
* Close a connection and remove it from the pool
*/
public function closeConnection(object $connection): void;
/**
* Get the current number of connections in the pool (including connections in use and unused connections)
*/
public function getConnectionCount(): int;
/**
* Close connections in the pool (not including connections that are currently being used)
*/
public function closeConnections(): void;
/**
* Set the method for creating connections in the connection pool
*/
public function setConnectionCreator(callable $connectionCreateHandler): self;
/**
* Set the method for destroying connections in the connection pool
*/
public function setConnectionCloser(callable $connectionDestroyHandler): self;
/**
* Set the heartbeat check method
*/
public function setHeartbeatChecker(callable $connectionHeartbeatHandler): self;
}