当前位置:首页 > PHP教程 > php高级应用 > 列表

php使用goto实现自动重启swoole、reactphp、workerman服务的代码

发布:smiling 来源: PHP粉丝网  添加日期:2022-02-27 10:20:35 浏览: 评论:0 

在平时使用swoole进行开发中,常常遇到这种问题,改了代码之后,手动ctrl+c中断服务,再敲命令重启服务,频繁地重启,感觉心很累。

php提供了inotify扩展,调用linux的inotify系统调用,监控文件的变化.

这时候就产生了一个想法,我开一个主进程监控文件变化,再开一个子进程运行swoole服务,主进程监听到文件变化之后,干掉子进程,然后再开一个子进程运行swoole服务. 子进程如果想优雅地退出,安装个信号处理器,在退出之前做一些操作。

  1. <?php 
  2.  
  3. //index.php 
  4.  
  5. require './vendor/autoload.php'; 
  6.  
  7. Restart: 
  8.  
  9. $pid = pcntl_fork(); 
  10.  
  11. if ($pid > 0) { 
  12.   $fd = inotify_init(); 
  13.   $watch_descriptor = inotify_add_watch($fd, './src/', IN_MODIFY); 
  14.  
  15.   $events = inotify_read($fd); 
  16.  
  17.   posix_kill($pid, SIGTERM); 
  18.     
  19.   fclose($fd); 
  20.  
  21.   pcntl_wait($status); 
  22.  
  23.   goto Restart; 
  24. } elseif ($pid == 0) { 
  25.   \Church\Application::run(); 
  26. } else { 
  27.   exit(0); 
  28. } 
  29.  
  30. <?php 
  31. namespace Church; 
  32.  
  33. /** 
  34. use Psr\Http\Message\ServerRequestInterface; 
  35. use React\Http\Response; 
  36. use React\Http\Server; 
  37. **/ 
  38.  
  39. class Application 
  40. { 
  41.   public static function run() 
  42.   { 
  43.   /** 
  44.     $loop = \React\EventLoop\Factory::create(); 
  45.  
  46.     $loop->addSignal(SIGTERM, function() use ($loop) { 
  47.       $loop->stop(); 
  48.     }); 
  49.  
  50.     $server = new Server(function (ServerRequestInterface $request) { 
  51.  
  52.       return new Response( 
  53.         200, 
  54.         array( 
  55.           'Content-Type' => 'text/plain' 
  56.         ), 
  57.         "Hello World1!\n" 
  58.       ); 
  59.     }); 
  60.  
  61.     $socket = new \React\Socket\Server(8080, $loop); 
  62.     $server->listen($socket); 
  63.  
  64.     $loop->run(); 
  65.   **/ 
  66.     //高性能HTTP服务器 
  67.     $http = new \Swoole\Http\Server("127.0.0.1", 9501); 
  68.  
  69.     $http->on("start", function ($server) { 
  70.       echo "Swoole http server is started at http://127.0.0.1:9501\n"; 
  71.     }); 
  72.  
  73.     $http->on("request", function ($request, $response) { 
  74.       $response->header("Content-Type", "text/plain"); 
  75.       $response->end("Hello World1\n"); 
  76.     }); 
  77.  
  78.     $http->start(); 
  79.  
  80.   } 
  81. } 

个人觉得这里最优雅的实现方式应该是用GOTO了。

Tags: swoole reactphp workerman

分享到: