问题描述
我正在开发一个 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;
?>
每次网络操作大约需要 5 秒才能完成,如果我提出 3 个请求,我的应用程序的响应时间总共会增加 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 的人来说,还有很多其他的实现 like这个).
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.
优点是:
- 可扩展性 - 您只需添加工作节点即可满足需求.这样,任务就可以并行运行了.
- 可靠性 - 现代队列管理器,如 RabbitMQ、ZeroMQ、Redis 等,都非常可靠.
这篇关于PHP中的异步函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!