PHP 中的异步函数调用 [英] Asynchronous Function Call in PHP

查看:27
本文介绍了PHP 中的异步函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 PHP Web 应用程序,我需要在请求中执行一些网络操作,例如根据用户的请求从远程服务器获取某人.

I am working on an a PHP web application and i need to perform some network operations in the request like fetching someone from remote server based on user's request.

是否可以在 PHP 中模拟异步行为,因为我必须将一些数据传递给一个函数并且还需要它的输出.

Is it possible to simulate asynchronous behavior in PHP given that i have to pass some data to a function and also need output from it.

我的代码是这样的:

<?php

     $data1 = processGETandPOST();
     $data2 = processGETandPOST();
     $data3 = processGETandPOST();

     $response1 = makeNetworkCall($data1);
     $response2 = makeNetworkCall($data2);
     $response3 = makeNetworkCall($data3);

     processNetworkResponse($response1);
     processNetworkResponse($response2);
     processNetworkResponse($response3);

     /*HTML and OTHER UI STUFF HERE*/

     exit;
?>

如果我发出 3 个请求,每个网络操作大约需要 5 秒才能完成,我的应用程序的响应时间总共增加了 15 秒.

Each network operation takes around 5 seconds to complete adding a total of 15 seconds to the response time of my application given i make 3 requests.

makeNetworkCall() 函数只执行 HTTP POST 请求.

The makeNetworkCall() function just do a HTTP POST request.

远程服务器是第 3 方 API,所以我无法控制那里.

The remote server is an 3rd party API so i don't have any control over there.

PS:请不要回答关于 AJAX 或其他事情的建议.我目前正在寻找是否可以通过 PHP 执行此操作,可能带有 C++ 扩展或类似的东西.

PS: Please do not answer giving suggestions about AJAX or Other things. I am currently looking if i can do this through PHP may be with an C++ extension or something like that.

推荐答案

现在,最好使用 queues 而不是线程(对于那些不使用 Laravel 的人,还有很多其他实现喜欢这个).

Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).

基本思想是,您的原始 PHP 脚本将任务或作业放入队列中.然后,您让队列作业工作程序在其他地方运行,从队列中取出作业并开始独立于原始 PHP 处理它们.

The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.

优点是:

  1. 可扩展性 - 您只需添加工作节点即可满足需求.这样,任务并行运行.
  2. 可靠性 - 现代队列管理器,例如 RabbitMQ、ZeroMQ、Redis 等,都非常可靠.

这篇关于PHP 中的异步函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆