简易swoole异步消息

编译安装

适用于php5.3以上版本

centOS中:
在此网站http://pecl.php.net/package/swoole选择合适的版本,我用的是1.10.5
#wget http://pecl.php.net/get/swoole-1.10.5.tgz
#tar -zxvf swoole-1.10.5.tgz
#cd swoole-1.10.5
#phpize
#./configure
#make
#make install
在php.ini加入一行:extension=swoole.so
重启apache,#systemctl restart httpd.service
通过php -m或phpinfo查看是否安装成功

服务端

$serv = new swoole_server("127.0.0.1", 9501);

//设置异步任务的工作进程数量
$serv->set(array('task_worker_num' => 4));

$serv->on('receive', function($serv, $fd, $from_id, $data) {
    //投递异步任务
    $task_id = $serv->task($data);
    echo "Dispath AsyncTask: id=$task_id\n";
});

//处理异步任务
$serv->on('task', function ($serv, $task_id, $from_id, $data) {
    sendMsg($data);
    //返回任务执行的结果
    $serv->finish("$data -> OK");
});

//处理异步任务的结果
$serv->on('finish', function ($serv, $task_id, $data) {
    write($task_id);
    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;
});

$serv->start();


function sendMsg($data){
    sleep(2);
    $array = json_decode($data,true);
    echo "接收到异步消息:" . $array['msg']."    消息类型:".$array['type']." 执行时间  ".time()."\n";
}
function write($task_id){
    echo "成功处理异步消息" . $task_id." 执行时间  ".time()."\n";
}

客户端

public function sendAction(){
            $client = new swoole_client(SWOOLE_SOCK_TCP);

            $msg = $_REQUEST["msg"];
            $type = $_REQUEST["type"];
            //连接到服务器
            $array['msg'] = $msg;
            $array['type'] = $type;
            $array = json_encode($array);
            if (!$client->connect('127.0.0.1', 9501, 0.5))
            {
                $this->write("connect failed.");
            }
            //向服务器发送数据
            if (!$client->send($array))
            {
                $this->write("send ".$array." failed.");
            }
            //关闭连接
            $client->close();

        $this->_result["returnResult"] = [
            'data' => "[".date("Y-m-d H:i:s")."]继续忙其他的".PHP_EOL,
            'time' => time(),
        ];

    }
    private function write($str){
        $path = "/tmp/synClient.log";
        $str = "[".date("Y-m-d H:i:s")."]".$str;
        $str .= PHP_EOL;
        file_put_contents($path,$str,FILE_APPEND);
    }

 

 

执行服务端

php server.php

ERROR swSocket_bind (ERROR 502): bind(127.0.0.1:9501) failed. Error: Address already in use [98]
 
lsof -i:9501  //查看9501对应的端口
 
kill 2294  //杀掉对应进程
 
kill -9 2294  //强制杀掉对应进程

php脚本

class Monitor
{
    const PORT = 9503;

    public function swoole(){
        $shell = "netstat -ntul|grep ".self::PORT."| grep LISTEN | wc -l";
        $result = shell_exec($shell);
        if($result == 0){
            //报警,发送短信或者邮箱给负责人
            //nohup命令 以守护进程形式重启,并将重启结果写入到文件中
            $restart_shell = "nohup php /var/www/html/swoole_imooc/thinkphp/server/ws.php > /var/www/html/swoole_imooc/thinkphp/server/t.txt &";
            $time = date("Y-m-d H:i:s",time());
            $date = date("Ymd",time());
            $file = "find /var/log/swoole -name {$date}.log | wc -l";
            //记录到日志文件
            if(shell_exec($file) == 0){
                shell_exec("touch /var/log/swoole/{$date}.log");
            }
            //将重启时间追加到日志文件中
            $log ="echo {$time}.'|restart' >> /var/log/swoole/{$date}.log";
            shell_exec($log);
            shell_exec($restart_shell);
        }else{
            echo date("Y-m-d H:i:s",time()).'success';
        }
    }
}
//执行一次
$monitor = new Monitor();
$monitor->swoole();




 守护swoole和关闭进程

public function openswoole(){
        $shell = "netstat -ntul|grep ".self::PORT."| grep LISTEN | wc -l";
        $result = shell_exec($shell);
        if($result == 0){
            //报警,发送短信或者邮箱给负责人
            //nohup命令 以守护进程形式重启,并将重启结果写入到文件中
            $restart_shell = "nohup /www/server/php/71/bin/php index.php api/goods/syncSend > /www/myout.log ";

            $result = shell_exec($restart_shell);
            echo "启动返回信息\n".$result;
        }else{
            echo date("Y-m-d H:i:s",time()).'进程已存在';
        }
    }

    //netstat -tunlp|grep "8083"|grep LISTEN |awk '{print $7}'|awk -F '/' '{print $1}'|xargs kill -9

    public function closeswoole(){
        $shell = "netstat -ntul|grep ".self::PORT."| grep LISTEN |awk '{print $7}'|awk -F '/' '{print $1}'|xargs kill -9";
        $result = shell_exec($shell);
        echo "关闭进程返回信息:\n".$result;

    }
 

 


                
ForDream:当前文章用户名 http://lowfk.com/index.php/2021/03/30/43.html:当前文章地址
THE END
分享
二维码
< <上一篇
下一篇>>