server-async.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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), static function ($command) use ($connection) {
  28. $connection->send(json_encode($command->resultRows));
  29. });
  30. return;
  31. case '/fortune':
  32. Http::header('Content-Type: text/html; charset=utf-8');
  33. $mysql->query('SELECT id,message FROM Fortune', static function ($command) use ($connection) {
  34. $arr = $command->resultRows;
  35. foreach ($arr as $row) {
  36. $fortune[$row['id']] = htmlspecialchars($row['message'], ENT_QUOTES, 'UTF-8');
  37. }
  38. $fortune[0] = 'Additional fortune added at request time.';
  39. asort($fortune);
  40. $html = '<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>';
  41. foreach ($fortune as $id => $message) {
  42. $html .= "<tr><td>$id</td><td>$message</td></tr>";
  43. }
  44. $connection->send($html.'</table></body></html>');
  45. });
  46. return;
  47. //case '/update':
  48. // Http::header('Content-Type: application/json');
  49. // return $connection->send(update());
  50. //case '/info':
  51. // Http::header('Content-Type: text/plain');
  52. // ob_start();
  53. // phpinfo();
  54. // $connection->send(ob_get_clean());
  55. //default:
  56. // Http::header('HTTP', true, 404);
  57. // $connection->send('Error 404');
  58. }
  59. };
  60. Worker::runAll();