server-async.php 2.7 KB

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