本篇文章给大家带来的内容是关于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父子进程管道通信的代码示例的详细内容。