coroutine-mysql.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. include '../vendor/autoload.php';
  3. use Smf\ConnectionPool\ConnectionPool;
  4. use Smf\ConnectionPool\Connectors\CoroutineMySQLConnector;
  5. use Swoole\Coroutine\MySQL;
  6. go(function () {
  7. // All MySQL connections: [10, 30]
  8. $pool = new ConnectionPool(
  9. [
  10. 'minActive' => 10,
  11. 'maxActive' => 30,
  12. 'maxWaitTime' => 5,
  13. 'maxIdleTime' => 20,
  14. 'idleCheckInterval' => 10,
  15. ],
  16. new CoroutineMySQLConnector,
  17. [
  18. 'host' => '127.0.0.1',
  19. 'port' => '3306',
  20. 'user' => 'root',
  21. 'password' => 'xy123456',
  22. 'database' => 'mysql',
  23. 'timeout' => 10,
  24. 'charset' => 'utf8mb4',
  25. 'strict_type' => true,
  26. 'fetch_mode' => true,
  27. ]
  28. );
  29. echo "Initializing connection pool\n";
  30. $pool->init();
  31. defer(function () use ($pool) {
  32. echo "Closing connection pool\n";
  33. $pool->close();
  34. });
  35. echo "Borrowing the connection from pool\n";
  36. /**@var MySQL $connection */
  37. $connection = $pool->borrow();
  38. $status = $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($status);
  42. });