Автор оригинала: David Wong.
Open-cmd/пул соединений-это универсальный пул соединений на основе целого, который часто используется в качестве пула соединений с базой данных.
полагаться на
| PHP | |
| .2.9 Рекомендую 4.2.13+ | Свул |
устанавливать
Установите через Composer.
composer require "open-smf/connection-pool:~1.0"
Воспользуйся
Еще примеры.
- Доступные разъемы
| Пример Swool\Сопрограммы\MySQL | Сопрограммный соединитель MySQL |
| Swool\Сопрограмма\Пример PostgreSQL, компиляции, когда вам нужно добавить параметры– включить-сопрограмма-postgresql | Соединитель сопрограммы PostgreSQL |
| Пример Swool\Сопрограммы\Redis | Сопрограмма RedisConnector |
| Красный-это, например, необходимо установить redis | Соединитель Php Redis |
| Ваши интерфейсы соединителя должны быть реализованы Интерфейс соединителя Любой объект может быть использован в качестве экземпляра соединения | Ваш Соединитель |
- Основное использование
use Smf\ConnectionPool\ConnectionPool;
use Smf\ConnectionPool\Connectors\CoroutineMySQLConnector;
use Swoole\Coroutine\MySQL;
go(function () {
// MySQL Connection Number Interval: [10, 30]
$pool = new ConnectionPool(
[
'minActive' => 10,
'maxActive' => 30,
'maxWaitTime' => 5,
'maxIdleTime' => 20,
'idleCheckInterval' => 10,
],
New Coroutine MySQL Connector, // specifies the connector instance, where you use the collaborative MySQL connector to create a database connection pool for the collaborative MySQL
[
'host' => '127.0.0.1',
'port' => '3306',
'user' => 'root',
'password' => 'xy123456',
'database' => 'mysql',
'timeout' => 10,
'charset' => 'utf8mb4',
'strict_type' => true,
'fetch_mode' => true,
]
);
Echo "Initialize connection pool... n";
$pool->init();
defer(function () use ($pool) {
Echo "Close connection pool... n";
$pool->close();
});
Echo "Loan connections from connection pools... n";
/**@var MySQL $connection */
$connection = $pool->borrow();
// Execute query statements
$status = $connection->query('SHOW STATUS LIKE "Threads_connected"');
Echo "Return the connection as soon as possible \ n";
$pool->return($connection);
var_dump($status);
});- Использование на раздутом сервере
use Smf\ConnectionPool\ConnectionPool;
use Smf\ConnectionPool\ConnectionPoolTrait;
use Smf\ConnectionPool\Connectors\CoroutineMySQLConnector;
use Smf\ConnectionPool\Connectors\PhpRedisConnector;
use Swoole\Coroutine\MySQL;
use Swoole\Http\Request;
use Swoole\Http\Response;
use Swoole\Http\Server;
class HttpServer
{
use ConnectionPoolTrait;
protected $swoole;
public function __construct(string $host, int $port)
{
$this->swoole = new Server($host, $port);
$this->setDefault();
$this->bindWorkerEvents();
$this->bindHttpEvent();
}
protected function setDefault()
{
$this->swoole->set([
'daemonize' => false,
'dispatch_mode' => 1,
'max_request' => 8000,
'open_tcp_nodelay' => true,
'reload_async' => true,
'max_wait_time' => 60,
'enable_reuse_port' => true,
'enable_coroutine' => true,
'http_compression' => false,
'enable_static_handler' => false,
'buffer_output_size' => 4 * 1024 * 1024,
'worker_num'=> 4, // Each Worker has a separate connection pool
]);
}
protected function bindHttpEvent()
{
$this->swoole->on('Request', function (Request $request, Response $response) {
$pool1 = $this->getConnectionPool('mysql');
/**@var MySQL $mysql */
$mysql = $pool1->borrow();
$status = $mysql->query('SHOW STATUS LIKE "Threads_connected"');
// After using the connection, return it as soon as possible
$pool1->return($mysql);
$pool2 = $this->getConnectionPool('redis');
/**@var Redis $redis */
$redis = $pool2->borrow();
$clients = $redis->info('Clients');
// After using the connection, return it as soon as possible
$pool2->return($redis);
$json = [
'status' => $status,
'clients' => $clients,
];
// Other logic
// ...
$response->header('Content-Type', 'application/json');
$response->end(json_encode($json));
});
}
protected function bindWorkerEvents()
{
$createPools = function () {
// All MySQL connection number intervals: [4 Workers * 2 = 8, 4 workers * 10 = 40]
$pool1 = new ConnectionPool(
[
'minActive' => 2,
'maxActive' => 10,
],
new CoroutineMySQLConnector,
[
'host' => '127.0.0.1',
'port' => '3306',
'user' => 'root',
'password' => 'xy123456',
'database' => 'mysql',
'timeout' => 10,
'charset' => 'utf8mb4',
'strict_type' => true,
'fetch_mode' => true,
]);
$pool1->init();
$this->addConnectionPool('mysql', $pool1);
// All Redis connection number intervals: [4 Workers * 5 = 20, 4 workers * 20 = 80]
$pool2 = new ConnectionPool(
[
'minActive' => 5,
'maxActive' => 20,
],
new PhpRedisConnector,
[
'host' => '127.0.0.1',
'port' => '6379',
'database' => 0,
'password' => null,
]);
$pool2->init();
$this->addConnectionPool('redis', $pool2);
};
$closePools = function () {
$this->closeConnectionPools();
};
// Create MySQL and Redis connection pools when Worker starts
$this->swoole->on('WorkerStart', $createPools);
// When Worker exits normally or wrongly, close the connection pool and release the connection
$this->swoole->on('WorkerStop', $closePools);
$this->swoole->on('WorkerError', $closePools);
}
public function start()
{
$this->swoole->start();
}
}
// Enabling Runtime to enable PhpRedis to extend one-key collaboration
Swoole\Runtime::enableCoroutine(true);
$server = new HttpServer('0.0.0.0', 5200);
$server->start();- Я был использован в производственной среде со стабильной производительностью.
вклад
Github, добро пожаловать в Star & PR.
Оригинал: “https://developpaper.com/universal-connection-pool-database-connection-pool-based-on-wool/”