PHP 中的异步 HTTP 请求 [英] Asynchronous HTTP requests in PHP

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

问题描述

有没有什么理智的方法可以在 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.

您还可以将请求队列存储在数据库中.一个单独的后台进程将拉取作业、执行它并保存输出,可能会在数据库中设置一个标志,您的 Web 进程可以检查该标志.

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屋!

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