当前位置:Gxlcms > PHP教程 > swoole_process父子进程管道通信的代码示例

swoole_process父子进程管道通信的代码示例

时间:2021-07-01 10:21:17 帮助过:9人阅读

本篇文章给大家带来的内容是关于swoole_process父子进程管道通信的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

话不多说直接上代码

创建的子进程:

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:

/**
     * @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即可实现一边发消息一边接收
  • 其他的后续补充

以上就是swoole_process父子进程管道通信的代码示例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行