MysqlSwoole.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. use Swoole\Database\PDOConfig;
  3. use Swoole\Database\PDOPool;
  4. class MysqlSwoole
  5. {
  6. protected Pool|PDOPool $pool;
  7. public function __construct($size)
  8. {
  9. $config = (new PDOConfig())
  10. ->withDriver('mysql')
  11. ->withHost('tfb-database')
  12. ->withPort(3306)
  13. ->withDbName('hello_world')
  14. ->withUsername('benchmarkdbuser')
  15. ->withPassword('benchmarkdbpass');
  16. $this->pool = new PDOPool($config, $size);
  17. }
  18. function db(): array
  19. {
  20. $pdo = $this->pool->get();
  21. $stmt = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  22. $stmt->execute([mt_rand(1, 10000)]);
  23. $result = $stmt->fetch(PDO::FETCH_ASSOC);
  24. $this->pool->put($pdo);
  25. return $result;
  26. }
  27. function query($request): array
  28. {
  29. $query_count = 1;
  30. $q = (int)$request->get('q');
  31. if ($q > 1) {
  32. $query_count = min($q, 500);
  33. }
  34. $pdo = $this->pool->get();
  35. $stmt = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  36. $arr = [];
  37. while ($query_count--) {
  38. $stmt->execute([mt_rand(1, 10000)]);
  39. $arr[] = $stmt->fetch(PDO::FETCH_ASSOC);
  40. }
  41. $this->pool->put($pdo);
  42. return $arr;
  43. }
  44. function update($request): array
  45. {
  46. $query_count = 1;
  47. $q = (int)$request->get('q');
  48. if ($q > 1) {
  49. $query_count = min($q, 500);
  50. }
  51. $arr = [];
  52. $pdo = $this->pool->get();
  53. $world = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  54. $update = $pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  55. while ($query_count--) {
  56. $id = mt_rand(1, 10000);
  57. $world->execute([$id]);
  58. $item = $world->fetch(PDO::FETCH_ASSOC);
  59. $update->execute(
  60. [$item['randomNumber'] = mt_rand(1, 10000), $id]
  61. );
  62. $arr[] = $item;
  63. }
  64. $this->pool->put($pdo);
  65. return $arr;
  66. }
  67. function fortune(): string
  68. {
  69. $pdo = $this->pool->get();
  70. $stmt = $pdo->prepare('SELECT id,message FROM Fortune');
  71. $stmt->execute();
  72. $arr = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
  73. $this->pool->put($pdo);
  74. $arr[0] = 'Additional fortune added at request time.';
  75. asort($arr);
  76. $html = '';
  77. foreach ($arr as $id => $message) {
  78. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  79. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  80. }
  81. return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>$html</table></body></html>";
  82. }
  83. }