如何处理从一个客户端到一个PHP脚本的多个并行请求 [英] How to process multiple parallel requests from one client to one PHP script

查看:86
本文介绍了如何处理从一个客户端到一个PHP脚本的多个并行请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网页,当用户浏览该网页时,一个PHP脚本会立即发出多个(10-20)Ajax请求,根据请求中的参数,该脚本将返回包含高度聚合数据的不同报告. /p>

问题在于,许多报告需要大量的SQL调用才能获取必要的数据,并且在某些情况下,报告可能需要花费几秒钟来加载.
结果,由于一个客户端向同一个PHP脚本发送多个请求,您最终只能一次将报告缓慢加载到页面上.换句话说,报告的生成不是并行完成的,因此导致页面需要一段时间才能完全加载.

是否有任何方法可以解决PHP中的问题,并使并行处理从单个客户端到单个PHP脚本的所有请求,从而可以更快地加载页面及其所有报告?

谢谢.

解决方案

据我所知,可以在PHP中进行多线程. 看看 pthreads扩展.

您可以做的是使报表的生成部分/脚本功能并行执行.这样可以确保每个函数都在其自己的线程中执行,并且可以更快地检索到您的结果.另外,将并发线程的最大数量设置为< = 10,这样它就不会成为资源消耗.

此处是一个基本的教程,可以帮助您开始使用pthreads.

还有一些更多示例可能会有所帮助(特别是SQLWorker示例)

I have a webpage that when users go to it, multiple (10-20) Ajax requests are instantly made to a single PHP script, which depending on the parameters in the request, returns a different report with highly aggregated data.

The problem is that a lot of the reports require heavy SQL calls to get the necessary data, and in some cases, a report can take several seconds to load.
As a result, because one client is sending multiple requests to the same PHP script, you end up seeing the reports slowly load on the page one at a time. In other words, the generating of the reports is not done in parallel, and thus causes the page to take a while to fully load.

Is there any way to get around this in PHP and make it possible for all the requests from a single client to a single PHP script to be processed in parallel so that the page and all its reports can be loaded faster?

Thank you.

解决方案

As far as I know, it is possible to do multi-threading in PHP. Have a look at pthreads extension.

What you could do is make the report generation part/function of the script to be executed in parallel. This will make sure that each function is executed in a thread of its own and will retrieve your results much sooner. Also, set the maximum number of concurrent threads <= 10 so that it doesn't become a resource hog.

Here is a basic tutorial to get you started with pthreads.

And a few more examples which could be of help (Notably the SQLWorker example in your case)

这篇关于如何处理从一个客户端到一个PHP脚本的多个并行请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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