【问题标题】:CURL resolving hosts much slower than plain file_get_contentsCURL 解析主机比普通 file_get_contents 慢得多
【发布时间】:2017-03-13 08:24:46
【问题描述】:

我在 localhost 上通过 URL 获得服务响应。当使用 CURL 并使用“localhost”作为域名时,第一个请求大约需要 150 毫秒,第二个请求需要 2 毫秒。当使用 IP 而不是“localhost”时,两个 CURL 请求都需要 2 毫秒。使用file_get_contents 时,无论是“localhost”还是IP,它总是大约3ms。

即使对于本地主机,什么也会导致这种延迟?

这里是测试代码:

$instance['port'] = 8192;
$instance['hostname' ] = 'localhost';
//$instance['hostname' ] = '127.0.0.1';


/* file_get_contents */
$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br>";

$time = microtime(true);
$response = file_get_contents('http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$queryTime = microtime(true) - $time;
echo "file_get_contents time: ".$queryTime."<br><br>";


/* CURL */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file1.txt');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$time = microtime(true);    
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br>";


curl_setopt($ch, CURLOPT_URL, 'http://'.$instance['hostname' ].':'.$instance['port'].'/file2.txt');
$time = microtime(true);    
curl_exec($ch);
$queryTime = microtime(true) - $time;
echo "CURL time: ".$queryTime."<br><br>";
curl_close($ch);

回复:

file_get_contents time: 0.0029559135437012
file_get_contents time: 0.0030159950256348

CURL time: 0.15396809577942
CURL time: 0.002269983291626

当使用 IP 而不是 localhost 时,响应如下:

file_get_contents time: 0.0025560855865479
file_get_contents time: 0.0034060478210449

CURL time: 0.0026850700378418
CURL time: 0.0027031898498535

【问题讨论】:

    标签: php curl php-curl


    【解决方案1】:

    正如here 所说,这可能是DNS 查找问题。您是否尝试将 localhost 添加到您的 etc/hosts 文件中?

    This answer 还建议编辑 hhtpd.conf 可能会对您有所帮助。

    【讨论】:

    • 本地主机在我的 /etc/hosts 中
    • 尝试将“ServerName 127.0.0.1:80”添加到 Apache conf。没用。
    • 嘿,停下!错误的方式。
    【解决方案2】:

    我试过你的脚本,它工作正常。首先 curl 调用慢一点。我的猜测,但请检查您是否激活了 IPv6,localhost 会转换为。

    尝试停用。

    【讨论】:

    • 尝试在所有接口上停用 IPv6。没有效果。
    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 2020-05-01
    • 2020-05-12
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多