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();

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...