在PHP中的异步HTTP请求 [英] Asynchronous HTTP requests in PHP
问题描述
有没有做异步PHP中的HTTP请求,不扔出去响应任何理智的方法是什么?即,类似于AJAX的东西 - PHP脚本启动请求,确实是自己的事情,后来,当接收到响应,回调函数/法或其他脚本处理响应
Is there any sane way to make a HTTP request asynchronously in PHP without throwing out the response? I.e., something similar to AJAX - the PHP script initiates the request, does it's own thing and later, when the response is received, a callback function/method or another script handles the response.
一个方法是穿过我的脑海 - 生成一个新的PHP进程另一个脚本为每个请求 - 第二个脚本执行的请求,等待响应,然后分析数据,并做什么应该,而原来的剧本继续产卵新进程。我怀疑,但是,关于在这种情况下的性能 - 必须有一些性能上的损失就不必每次都创建一个新进程
One approach has crossed my mind - spawning a new php process with another script for each request - the second script does the request, waits for the response and then parses the data and does whatever it should, while the original script goes on spawning new processes. I have doubts, though, about performance in this case - there must be some performance penalty from having to create a new process every time.
推荐答案
是的,这取决于你的网站的流量,产卵一个单独的PHP进程中运行的脚本可能是灾难性的。这将是更有效地使用了shell_exec()来启动一个后台进程,并将输出保存至你已经知道文件名,但即使这可能是资源密集的。
Yes, depending on the traffic of your site, spawning a separate PHP process for running a script could be devastating. It would be more efficient to use shell_exec() to start a background process that saves the output to a filename you already know, but even this could be resource intensive.
您也可以有存储在数据库中的请求队列中。一个单一的,独立的后台进程将拉动工作,执行它,并保存输出,可能是您的网络进程可以检查DB设置一个标志。
You could also have a request queue stored in a database. A single, separate background process would pull the job, execute it, and save the output, possibly setting a flag in the DB that your web process could check.
如果你打算使用DB队列的方式,使用curl_multi *类的功能,一次发送所有排队的请求。这将限制每次迭代的执行时间在后台进程最长请求时间
If you're going to use the DB queue approach, use curl_multi* class of functions to send all queued requests at once. This will limit the execution time of each iteration in your background process to the longest request time.
这篇关于在PHP中的异步HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!