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

php中Swoole的热更新实现代码实例

发布:smiling 来源: PHP粉丝网  添加日期:2022-04-16 14:10:37 浏览: 评论:0 

使用swoole_http_server替代php-fpm后,由于php长驻内存,修改了代码不能实时调试,需要去手动去重启服务,很是不方便,决定使用inotify来监控文件状态的改变,来给swoole发送reload信号,来实现swoole的热更新。

如何安装inotify就不写了,安装之后可以建立一个脚本文件,如php_reload.sh:

  1. #!/bin/sh 
  2. # src 需要监控的地址 
  3. src=/home/server/Project/test/app/ 
  4. /usr/bin/inotifywait -rmq -e create,modify,delete $src | while read event 
  5.  do 
  6.     /home/server/Project/test/bin/httpserver reload 
  7.  done 

linux shell 写swoole重启脚本

代码如下

  1. #!/bin/sh 
  2. kill `lsof -t -i:9501` 
  3. sleep 2 
  4. php /data/web/mircoweb/wwwroot/Public/swoole.php 
  5. sleep 1 
  6. netstat -ntlp 

如果不支持lsof命令 那就yum install lsof安装下吧

swoole服务平滑重启

1. reload.sh脚本

  1. echo "loading..." 
  2. pid="pidof live_name" 
  3. echo $pid 
  4. kill -USR1 $pid 
  5. echo "loading success" 

2. linux中执行

sh  reload.sh

代码用的原来只是自己加了一些操作流程

swoole_reload_server.php

  1. <?php 
  2. class Server 
  3. { 
  4.         private $serv; 
  5.         public function __construct() { 
  6.         $this->serv = new swoole_server("0.0.0.0", 9501); 
  7.         $this->serv->set(array( 
  8.             'worker_num' => 8, 
  9.             'daemonize' => false, 
  10.             'max_request' => 10000, 
  11.             'dispatch_mode' => 2, 
  12.             'debug_mode'=> 1, 
  13.         )); 
  14.         $this->serv->on('Start', array($this, 'onStart')); 
  15.         $this->serv->on('WorkerStart', array($this, 'onWorkerStart')); 
  16.         $this->serv->on('Connect', array($this, 'onConnect')); 
  17.         $this->serv->on('Receive', array($this, 'onReceive')); 
  18.         $this->serv->on('Close', array($this, 'onClose')); 
  19.         $this->serv->start(); 
  20.     } 
  21.     public function onStart( $serv ) { 
  22.         echo "Start\n"; 
  23.         cli_set_process_title("reload_master"); 
  24.     } 
  25.     public function onWorkerStart( $serv , $worker_id) { 
  26.         require_once "reload_page.php"; 
  27.         Test(); 
  28.     } 
  29.     public function onConnect( $serv, $fd, $from_id ) { 
  30.         echo "Client {$fd} connect\n"; 
  31.    
  32.     } 
  33.     public function onReceive( swoole_server $serv, $fd, $from_id, $data ) { 
  34.         echo "Get Message From Client {$fd}:{$data}\n"; 
  35.     } 
  36.     public function onClose( $serv, $fd, $from_id ) { 
  37.         echo "Client {$fd} close connection\n"; 
  38.     } 
  39. } 
  40. new Server(); 

reload.sh

  1. echo "Reloading..." 
  2. cmd=$(pidof reload_master) 
  3.    
  4. kill -USR1 "$cmd" 
  5. echo "Reloaded" 

reload_page.php

  1. <?php 
  2. /** 
  3.  * If you change this function and want 
  4.  * swoole_server to use the new function, 
  5.  * just run 'reload.sh' to send a restart 
  6.  * signal to swoole_server. 
  7.  */ 
  8. function Test() { 
  9.   echo "This is not a php file\n"; 
  10. }

Tags: Swoole热更新

分享到: