coroutine-runtime-pdo.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. include '../vendor/autoload.php';
  3. use Smf\ConnectionPool\ConnectionPool;
  4. use Smf\ConnectionPool\Connectors\PDOConnector;
  5. // Enable coroutine for PDO
  6. Swoole\Runtime::enableCoroutine();
  7. go(function () {
  8. // All PDO connections: [10, 30]
  9. $pool = new ConnectionPool(
  10. [
  11. 'minActive' => 10,
  12. 'maxActive' => 30,
  13. 'maxWaitTime' => 5,
  14. 'maxIdleTime' => 20,
  15. 'idleCheckInterval' => 10,
  16. ],
  17. new PDOConnector,
  18. [
  19. 'dsn' => 'mysql:host=127.0.0.1;port=3306;dbname=mysql;charset=utf8mb4',
  20. 'username' => 'root',
  21. 'password' => 'xy123456',
  22. 'options' => [
  23. \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
  24. \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
  25. \PDO::ATTR_TIMEOUT => 30,
  26. ],
  27. ]
  28. );
  29. echo "Initializing connection pool\n";
  30. $pool->init();
  31. defer(function () use ($pool) {
  32. echo "Close connection pool\n";
  33. $pool->close();
  34. });
  35. echo "Borrowing the connection from pool\n";
  36. /**@var \PDO $connection */
  37. $connection = $pool->borrow();
  38. $statement = $connection->query('SHOW STATUS LIKE "Threads_connected"');
  39. echo "Return the connection to pool as soon as possible\n";
  40. $pool->return($connection);
  41. var_dump($statement->fetch());
  42. });