PHP 中的异步 HTTP 请求
有没有什么明智的方法可以在 PHP 中异步发出 HTTP 请求而不丢弃响应? 即,类似于 AJAX - PHP 脚本发起请求,执行自己的操作,然后,当收到响应时,回调函数/方法或另一个脚本处理响应。
我想到了一种方法 - 为每个请求生成一个新的 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,根据站点的流量,生成一个单独的 PHP 进程来运行脚本可能会造成毁灭性的后果。 使用 shell_exec() 启动后台进程将输出保存到您已知的文件名会更有效,但即使这样也可能会占用大量资源。
您还可以将请求队列存储在数据库中。 一个单独的后台进程将拉取作业、执行它并保存输出,可能会在数据库中设置一个标志供您的 Web 进程检查。
如果您要使用数据库队列方法,请使用curl_multi* 函数类一次发送所有排队的请求。 这会将后台进程中每次迭代的执行时间限制为最长请求时间。
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.
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.
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.
V5 可能没有线程,但您可以创建利用进程内多任务处理的应用程序。
查看以下文章:“使用 PHP V5 开发多任务应用程序”
IBM DeveloperWorks。 您可以在这里找到它 http://www.ibm.com/ developerworks/web/library/os-php-multitask/
V5 may not be threaded, but you can create applications that exploit in-process multitasking.
Check out the following article: "Develop multitasking applications with PHP V5" from
IBM DeveloperWorks. You can find it here http://www.ibm.com/developerworks/web/library/os-php-multitask/