异步API中调用PHP [英] Asynchronous API calls in PHP

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

问题描述

我有需要做三个独立的API调用,合并结果的PHP脚本,并把它输出给用户。

I have a PHP script that needs to make three separate API calls, combine the results, and output it for the user.

的问题是,每个API调用大约需要5秒钟来执行。用3 API调用在每5秒,它需要约15秒来执行脚本。

The problem is that each API call takes about 5 seconds to execute. With 3 API calls at 5 seconds each, it take about 15 seconds to execute the script.

有没有办法,我能以某种方式启动三个API的方式同时通话,一旦最后一个完成后,合并的结果?如果可能的话我可能减少的时间长度从15到5秒,极大地提高了我的用户体验。

Is there a way that I can somehow start the three API calls simultaneously and once the last one finishes, combine the results? If that's possible I could potentially reduce the length of time from 15 to 5 seconds, dramatically improving my user's experience.

我研究了PHP的异步函数调用,但似乎没有被很多很好的选择。我希望有人在那里已经有类似的情况,发现了一个优雅的方式来处理这个问题。

I researched asynchronous function calls in PHP, but there doesn't seem to be a lot of good options. I'm hoping that someone out there has been in a similar situation and found an elegant way to handle this.

推荐答案

自己的PHP脚本是单线程的。有办法在PHP中使用 pcntl_fork 功能叉的子进程。但据我所知,这只有真正的CLI SAPI效果很好。与任何Web服务器SAPI的,无论是它的越野车还是不支持。

PHP scripts by themselves are single threaded. There are ways to "fork" child processes in PHP using pcntl_fork function. But as far as I know, this only really works well with the CLI sapi. With any of the web server sapi's, either it's buggy or not supported.

如果你有一个来自Web请求启动它,你可以尝试使用了shell_exec 产卵主在后台PHP CLI过程(追加&安培; 末),然后利用pcntl_fork的瓜分工作

If you have to initiate it from a web request, you could try using shell_exec to spawn a master PHP CLI process in the background (append & at the end), and then make use of pcntl_fork to divide up the work.

如果你只是等待Web请求,我会按照使用的 curl_multi 功能。但是,如果正确使用分叉可以,如果你有其他的密集型任务是有用的。

If you're just waiting on web requests, I would follow Dagon's suggestion of using the curl_multi functions. But forking can be useful if you have other intensive tasks, if used correctly.

这篇关于异步API中调用PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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