swoole_process父子进程管道通信的代码示例
发布:smiling 来源: PHP粉丝网 添加日期:2020-01-16 15:10:20 浏览: 评论:0
本篇文章给大家带来的内容是关于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即可实现一边发消息一边接收
其他的后续补充
Tags: swoole_process
相关文章
- ·swoole_process实现进程池的方法示例(2021-11-01)
推荐文章
热门文章
最新评论文章
- 写给考虑创业的年轻程序员(10)
- PHP新手上路(一)(7)
- 惹恼程序员的十件事(5)
- PHP邮件发送例子,已测试成功(5)
- 致初学者:PHP比ASP优秀的七个理由(4)
- PHP会被淘汰吗?(4)
- PHP新手上路(四)(4)
- 如何去学习PHP?(2)
- 简单入门级php分页代码(2)
- php中邮箱email 电话等格式的验证(2)