gpt4 book ai didi

php - 使用非阻塞流在 PHP 中并行化 REST-Api 请求?

转载 作者:可可西里 更新时间:2023-11-01 16:31:08 26 4
gpt4 key购买 nike

考虑以下场景:

  • http://www.restserver.com/example.php 返回一些我想在我的网络应用程序中使用的内容。

  • 我不想使用 ajax 加载它(SEO 问题等)

  • 我的页面需要 100 毫秒才能生成,REST 资源也需要 100 毫秒才能加载。

  • 我们假设我的网站的 100 毫秒生成时间发生在我开始使用 REST 资源之前。之后的事情可以忽略不计。

示例代码:

我网站的Index.php

<?
do_some_heavy_mysql_stuff(); // takes 100 ms
get_rest_resource(); // takes 100 ms
render_html_with_data_from_mysql_and_rest(); // takes neglectable amount of time
?>

网站生成需要约 200 毫秒。

我想把它变成:

<?
Restclient::initiate_rest_loading(); // takes 0ms
do_some_heavy_mysql_stuff(); // takes 100 ms
Restclient::get_rest_resource(); // takes 0 ms because 100 ms have already passed since initiation
render_html_with_data_from_mysql_and_rest(); // takes neglectable amount of time
?>

网站生成需要约 100 毫秒。

为了实现这一点,我考虑过使用这样的东西:

(我很确定这段代码不会起作用,因为这个问题都是关于如何完成它,以及它是否可能。我只是认为一些天真的代码可以最好地证明它)

class Restclient {
public static $buffer;
public static function initiate_rest_loading() {
// open resource
$handle = fopen ("http://www.restserver.com/example.php", "r");
// set to non blocking so fgets will return immediately
stream_set_blocking($handle,0);
// initate loading, but return immediately to continue website generation
fgets($handle, 40960);
}
public static function get_rest_resource() {
// set stream to blocking again because now we really want the data
stream_set_blocking($handle,1);
// get the data and save it so templates can work with it
self::$buffer = fgets($handle, 40960); templates
}
}

最后一个问题:

  • 这可能吗?如何实现?

  • 我需要注意什么(内部缓冲区溢出、流长度等)

  • 有没有更好的方法?

  • 这是否适用于 http 资源?

  • 任何输入都适用!

我希望我解释的很清楚。如果有任何不清楚的地方,请发表评论,以便我重新措辞!

最佳答案

作为“任何输入表示赞赏”,这是我的:

  • 你想要的是异步(你想要做某事,而其他事情正在“后台”完成)。

为了解决你的问题,我想到了这个:

  1. 在两个不同的 PHP 脚本中将 do_some_heavy_mysql_stuffget_rest_resource 分开。

  2. 使用 cURL 的“多”能力进行同时请求。请检查:

这样,您可以同时执行两个脚本。使用cURL multi特性,可以同时调用http://example.com/do_some_heavy_mysql_stuff.phphttp://example.com/get_rest_resource.php,然后在结果可用时立即使用。

这些是我的第一个想法,我将与您分享。也许有不同且更有趣的方法......祝你好运!

关于php - 使用非阻塞流在 PHP 中并行化 REST-Api 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6873088/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com