微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

swoole http_server 多进程并使用多进程处理消息

<?PHP
$http = new swoole_http_server("0.0.0.0", 9511);
$http->set([
                 'worker_num' =>3, //工作进程数
                'daemonize' => true, //是否后台运行
            ]);
$http->on('request','Run');

function Run($request, $response)
{
    $url=$request->server['request_uri'];
    if($url!='/favicon.ico'){
        $m = [1,2,3,4,5,6,7,8,9];
        p($m);
    }
    $response->end('首页');
}

function p($messages)
{
    $worker_num = 5;
    $process_pool = [];

    $process= null;
    $pid = posix_getpid();
    $customMsgKey = 1;
    $mod = 2 | swoole_process::IPC_NowAIT;//这里设置消息队列为非阻塞模式

    for($i=0;$i<$worker_num; $i++) {
        $process=new swoole_process('sub_process');
        $process->useQueue($customMsgKey, $mod);
        $process->start();
        $pid = $process->pid;
        $process_pool[$pid] = $process;
    }
    //由于所有进程是共享使用一个消息队列,所以只需向一个子进程发送消息即可
    $process = current($process_pool);
    foreach ($messages as $msg) {
        $process->push($msg);
    }

}


function sub_process(swoole_process $worker)
{
        sleep(1); //防止父进程还未往消息队列中加入内容直接退出
        // echo "worker ".$worker->pid." started".PHP_EOL;
        while($msg = $worker->pop()){
            echo $msg;
            if ($msg === false) {
                break;
            }
            $sub_pid = $worker->pid;
            // echo "[$sub_pid] msg : $msg".PHP_EOL;
            file_put_contents(__DIR__.'/a.txt',"[$sub_pid] msg : $msg".PHP_EOL,FILE_APPEND);
            sleep(1);//这里的sleep模拟任务耗时,否则可能1个worker就把所有信息全接受了
        }
        // echo "worker ".$worker->pid." exit".PHP_EOL;
        $worker->exit(0);
}

$http->start();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐