server-async.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. require_once __DIR__.'/vendor/autoload.php';
  3. use Workerman\Protocols\Http;
  4. use Workerman\Worker;
  5. $http_worker = new Worker('http://0.0.0.0:8080');
  6. $http_worker->count = shell_exec('nproc');
  7. $http_worker->onWorkerStart = static function() {
  8. global $mysql;
  9. $loop = Worker::getEventLoop();
  10. $mysql = new React\MySQL\Connection($loop, [
  11. 'host' => 'tfb-database',
  12. 'dbname' => 'hello_world',
  13. 'user' => 'benchmarkdbuser',
  14. 'passwd' => 'benchmarkdbpass'
  15. ]);
  16. $mysql->on('error', function($e){
  17. echo $e;
  18. });
  19. $mysql->connect(function ($e) {});
  20. };
  21. $http_worker->onMessage = static function ($connection) {
  22. global $mysql;
  23. Http::header('Date: '.gmdate('D, d M Y H:i:s').' GMT');
  24. switch (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)) {
  25. case '/db':
  26. Http::header('Content-Type: application/json');
  27. $mysql->query('SELECT id,randomNumber FROM World WHERE id='.mt_rand(1, 10000),
  28. static function ($command) use ($connection) {
  29. $connection->send(json_encode($command->resultRows, JSON_NUMERIC_CHECK));
  30. }
  31. );
  32. return;
  33. case '/fortune':
  34. Http::header('Content-Type: text/html; charset=utf-8');
  35. $mysql->query('SELECT id,message FROM Fortune',
  36. static function ($command) use ($connection) {
  37. $arr = $command->resultRows;
  38. foreach ($arr as $row) {
  39. $fortune[$row['id']] = htmlspecialchars($row['message'], ENT_QUOTES, 'UTF-8');
  40. }
  41. $fortune[0] = 'Additional fortune added at request time.';
  42. asort($fortune);
  43. $html = '<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>';
  44. foreach ($fortune as $id => $message) {
  45. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  46. }
  47. $connection->send($html.'</table></body></html>');
  48. }
  49. );
  50. return;
  51. //case '/update':
  52. // Http::header('Content-Type: application/json');
  53. // return $connection->send(update());
  54. //case '/info':
  55. // Http::header('Content-Type: text/plain');
  56. // ob_start();
  57. // phpinfo();
  58. // $connection->send(ob_get_clean());
  59. //default:
  60. // Http::header('HTTP', true, 404);
  61. // $connection->send('Error 404');
  62. }
  63. };
  64. Worker::runAll();