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();
上一篇:如何使用PHP批量生成以太坊账户


下一篇:建议将Java源码从1.4.2升级到1.6.0_10? (跳过1.5)