dynamic-testing.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. include '../vendor/autoload.php';
  3. use Smf\ConnectionPool\ConnectionPool;
  4. use Smf\ConnectionPool\Connectors\PDOConnector;
  5. use Swoole\Coroutine;
  6. Swoole\Runtime::enableCoroutine();
  7. go(function () {
  8. // All MySQL 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. $pool->init();
  30. // For debug
  31. $peakCount = 0;
  32. swoole_timer_tick(1000, function () use ($pool, &$peakCount) {
  33. $count = $pool->getConnectionCount();
  34. $idleCount = $pool->getIdleCount();
  35. if ($peakCount < $count) {
  36. $peakCount = $count;
  37. }
  38. echo "Pool connection count: $count, peak count: $peakCount, idle count: $idleCount\n";
  39. });
  40. while (true) {
  41. $count = mt_rand(1, 45);
  42. echo "Query count: $count\n";
  43. for ($i = 0; $i < $count; $i++) {
  44. go(function () use ($pool) {
  45. /**@var \PDO $pdo */
  46. $pdo = $pool->borrow();
  47. defer(function () use ($pool, $pdo) {
  48. $pool->return($pdo);
  49. });
  50. $statement = $pdo->query('show status like \'Threads_connected\'');
  51. $ret = $statement->fetch();
  52. if (!isset($ret['Variable_name'])) {
  53. echo "Invalid query result: \n", print_r($ret, true);
  54. }
  55. echo $ret['Variable_name'] . ': ' . $ret['Value'] . "\n";
  56. });
  57. }
  58. Coroutine::sleep(mt_rand(1, 15));
  59. }
  60. });