swoole_process父子進程管道通訊案例

話很少說直接上代碼

建立的子進程:redis

public function __construct()
    {
        $this->redis   = Container::get(SwooleRedis::class);//獲取異步redis獲取更高性能
        $this->process = new swoole_process(function (swoole_process $process) {
            return $this->process($process);
        }, false, SOCK_DGRAM);
        $this->process->name('Test_Gateway');
        $this->process->useQueue();
        $this->process->start();//啓動子進程
    }
    
    /**
     * 子進程處理邏輯
     * @param swoole_process $process
     */
    private function process(swoole_process $process)
    {
        $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //異步非阻塞
        
        $client->on("connect", function (swoole_client $cli) use ($process) {
            $process->write('connected');
        });
        
        $client->on("receive", function (swoole_client $cli, $data) use ($process) {
            $process->write($data);
        });
        
        $client->on("error", function (swoole_client $cli) use ($process) {
            $process->write('error');
        });
        
        $client->on("close", function (swoole_client $cli) use ($process) {
            $process->write('close');
        });
        
        if ($client->connect('127.0.0.1', 90, -1)) {
        
        } else {
            $process->write('網關鏈接失敗');
        }
        
        swoole_event_add($process->pipe,
            function ($pipe) use ($process, $client) {//讀取父進程管道消息
                $client->send($process->read());
            });
    }

父進程onWorkerStart:swoole

/**
     * @param swoole_server $serv
     * @param               $worker_id
     */
    public function onWorkerStart(\swoole_server $serv, $worker_id)
    {
        if ($worker_id === 0) {
            swoole_timer_tick(1000, function () {
                $this->process->write('ping');
            });
            $process = $this->process;
            swoole_event_add($process->pipe,
                function ($pipe) use ($process) {//獲取子進程的管道消息
                    echo "子進程消息:" . $process->read() . PHP_EOL;
                });
        }
    }
  • 子進程的client客戶端能夠忽略不計,本demo只是掩飾管道通訊的例子
  • 使用管道就不可使用消息隊列:$process_push()和$process->pop();
  • 理論上在父子進程各註冊一個event_loop便可實現一邊發消息一邊接收
  • 其餘的後續補充
相關文章
相關標籤/搜索