【发布时间】:2017-01-21 00:53:00
【问题描述】:
我正在尝试通过有效地处理 cURL 请求来加速我的网站。我正在运行大约 3 个请求,其中两个请求到同一台服务器。这是我的代码:
$profile = curl_init();
curl_setopt($profile, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($profile, CURLOPT_RETURNTRANSFER, true);
curl_setopt($profile, CURLOPT_FAILONERROR, true);
curl_setopt($profile, CURLOPT_URL,"https://owapi.net/api/v2/u/".$battletag."/stats/".$mode."?platform=".$platform);
$result = curl_exec($profile); //grab API data
curl_close($profile);
$stats = json_decode($result, true); //decode JSON data
$profile1 = curl_init();
curl_setopt($profile1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($profile1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($profile1, CURLOPT_FAILONERROR, true);
curl_setopt($profile1, CURLOPT_URL,"https://api.lootbox.eu/".$platform."/us/".$battletag."/profile");
$result1 = curl_exec($profile1); //grab API data
curl_close($profile1);
$stats1 = json_decode($result1, true);
$hero_stats = curl_init();
curl_setopt($hero_stats, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($hero_stats, CURLOPT_RETURNTRANSFER, true);
curl_setopt($hero_stats, CURLOPT_FAILONERROR, true);
curl_setopt($hero_stats, CURLOPT_URL,"https://api.lootbox.eu/".$platform."/us/".$battletag."/competitive-play/heroes");
$hero_play_time = curl_exec($hero_stats); //grab API data
curl_close($hero_stats);
$heroes_info = json_decode($hero_play_time, true);
如何在不重新启动连接的情况下同时处理这些请求?我想加快我网站的加载时间,因为现在需要很长时间。任何帮助,将不胜感激。我听说过 curl_multi_init() 方法,但我不确定如何正确使用它。欢迎提供任何帮助。
谢谢。
【问题讨论】:
-
也许不是一种使连接本身更快的方法,但您是否考虑过缓存?(鉴于这是一种可行的可能性)。话虽如此,您对此无能为力,这主要取决于您获得的数据量(如字面量,越少越好)以及相关 API 的速度。
-
@Andrew 我没有,这实际上是个好主意。有可能,我只需要为用户添加某种缓存更新来更新他们的结果。
-
好了。我建议PHP Redis(它实际上是用 C 语言编写的,顾名思义,而且速度非常快,除非你在多台服务器上运行,否则这是个坏主意)。如果您在多台服务器上运行并且需要保持同步,那么我想 Memcache 是一个不错的选择。
-
其实我收回了这一点,PHP Redis 显然支持多个服务器。 github.com/phpredis/phpredis/blob/master/arrays.markdown。我只是为了保持一致性而添加这个,我怀疑它与手头的问题有关。
-
要对 api 执行并行/并发调用,您可以使用
curl_multi_exec执行此操作。要以正确的方式使用它,请查看Doing curl_multi_exec the right way
标签: php json http curl python-requests