server.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. require_once __DIR__.'/vendor/autoload.php';
  3. use Swoole\Coroutine;
  4. use Workerman\Worker;
  5. use Workerman\Events\Swow;
  6. use Workerman\Events\Swoole;
  7. use Workerman\Events\Select;
  8. use Workerman\Protocols\Http\Response;
  9. $test_type = getenv('TEST_TYPE') ?: 'default';
  10. $process = getenv('PROCESS_MULTIPLIER') ?: 1;
  11. $pool_size = getenv('POOL_SIZE') ?: 2;
  12. $process_count = (int) shell_exec('nproc') * $process;
  13. $event_loop = getenv('EVENT_LOOP');
  14. $db = $date = null;
  15. $http_worker = new Worker('http://0.0.0.0:8080');
  16. $http_worker->reusePort = true;
  17. $http_worker->count = $process_count;
  18. $http_worker->onWorkerStart = static function () use ($test_type, $pool_size, &$db, &$date) {
  19. $db = match ($test_type) {
  20. 'pgsql' => new Pgsql(),
  21. 'mysql' => new Mysql(),
  22. 'pgsql-swow' => new PgsqlSwow($pool_size),
  23. 'mysql-swow' => new MysqlSwow($pool_size),
  24. 'pgsql-swoole' => new PgsqlSwoole($pool_size),
  25. 'mysql-swoole' => new MysqlSwoole($pool_size),
  26. 'default' => new Mysql(),
  27. };
  28. $date = new Date();
  29. };
  30. Worker::$eventLoopClass = "Workerman\\Events\\$event_loop";
  31. if ($event_loop === 'Swoole') {
  32. Coroutine::set(['hook_flags' => SWOOLE_HOOK_ALL]);
  33. }
  34. $http_worker->onMessage = static function ($connection, $request) use (&$db, &$date) {
  35. switch ($request->path()) {
  36. case '/plaintext':
  37. $connection->headers = [
  38. 'Content-Type' => 'text/plain',
  39. 'Date' => $date->date
  40. ];
  41. return $connection->send('Hello, World!');
  42. case '/json':
  43. $connection->headers = [
  44. 'Content-Type' => 'application/json',
  45. 'Date' => $date->date
  46. ];
  47. return $connection->send(json_encode(['message' => 'Hello, World!']));
  48. case '/db':
  49. $connection->headers = [
  50. 'Content-Type' => 'application/json',
  51. 'Date' => $date->date
  52. ];
  53. return $connection->send(json_encode($db->db()));
  54. case '/fortunes':
  55. $connection->headers = [
  56. 'Date' => $date->date
  57. ];
  58. return $connection->send($db->fortune());
  59. case '/query':
  60. $connection->headers = [
  61. 'Content-Type' => 'application/json',
  62. 'Date' => $date->date
  63. ];
  64. return $connection->send(json_encode($db->query($request)));
  65. case '/update':
  66. $connection->headers = [
  67. 'Content-Type' => 'application/json',
  68. 'Date' => $date->date
  69. ];
  70. return $connection->send(json_encode($db->update($request)));
  71. }
  72. return $connection->send(new Response(404, [
  73. 'Content-Type' => 'text/plain',
  74. 'Date' => $date->date
  75. ], '404 Not Found'));
  76. };
  77. Worker::runAll();