MysqlSwoole.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. $count = min(max((int) $request->get('q'), 1), 500);
  30. $pdo = $this->pool->get();
  31. $stmt = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  32. $arr = [];
  33. while ($count--) {
  34. $stmt->execute([mt_rand(1, 10000)]);
  35. $arr[] = $stmt->fetch(PDO::FETCH_ASSOC);
  36. }
  37. $this->pool->put($pdo);
  38. return $arr;
  39. }
  40. function update($request): array
  41. {
  42. $count = min(max((int) $request->get('q'), 1), 500);
  43. $arr = [];
  44. $pdo = $this->pool->get();
  45. $world = $pdo->prepare('SELECT id,randomNumber FROM World WHERE id=?');
  46. $update = $pdo->prepare('UPDATE World SET randomNumber=? WHERE id=?');
  47. while ($count--) {
  48. $id = mt_rand(1, 10000);
  49. $world->execute([$id]);
  50. $item = $world->fetch(PDO::FETCH_ASSOC);
  51. $update->execute(
  52. [$item['randomNumber'] = mt_rand(1, 10000), $id]
  53. );
  54. $arr[] = $item;
  55. }
  56. $this->pool->put($pdo);
  57. return $arr;
  58. }
  59. function fortune(): string
  60. {
  61. $pdo = $this->pool->get();
  62. $stmt = $pdo->prepare('SELECT id,message FROM Fortune');
  63. $stmt->execute();
  64. $arr = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
  65. $this->pool->put($pdo);
  66. $arr[0] = 'Additional fortune added at request time.';
  67. asort($arr);
  68. $html = '';
  69. foreach ($arr as $id => $message) {
  70. $message = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
  71. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  72. }
  73. return "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>$html</table></body></html>";
  74. }
  75. }