0

我目前有这个代码。它从 api 获取每小时的 json 数据文件和全天的文件。然后它缓存结果以便更快地获取。目前,获取所有文件并使用它们需要 ~10 秒(无缓存),使用缓存执行需要 ~1 秒,但当缓存过时时,使用以下方法(使用缓存)需要 ~80 秒。显然还有其他代码正在运行,但这是缓慢的一点。$this->hours有 24 个元素。

有没有更快的方法来获取文件并缓存它们?

/**
 * Get the weather data from forecast.io
 * @return array The overall weather data
 */
public function getData($kernelDir)
{
    $apiSite = 'https://api.forecast.io/forecast/';
    $url = $apiSite . $this->apiKey . '/' . $this->latitude . ',' . $this->longitude;

    if (!file_exists($kernelDir . '/cache/api/' . $this->latitude . '.' . $this->longitude))
    {
        $weatherFile = @file_get_contents($url);
        $fp = fopen($kernelDir . '/cache/api/' . $this->latitude . '.' . $this->longitude, 'w+');
        fwrite($fp, $weatherFile);
        fclose($fp);
    }
    else {
        $weatherFile = @file_get_contents($kernelDir . '/cache/api/' . $this->latitude . '.' . $this->longitude);
    }

    $this->weatherData['day'] = @json_decode($weatherFile, true);

    $this->getHours();

    foreach ($this->hours as $normal => $unixTimestamp)
    {
        $url = $apiSite . $this->apiKey . '/' . $this->latitude . ',' . $this->longitude . ',' . $unixTimestamp;

        if (!file_exists($kernelDir . '/cache/api/' . $this->latitude . '.' . $this->longitude . '.' . $unixTimestamp))
        {
            $weatherFile = @file_get_contents($url);
            $fp = fopen($kernelDir . '/cache/api/' . $this->latitude . '.' . $this->longitude . '.' . $unixTimestamp, 'w+');
            fwrite($fp, $weatherFile);
            fclose($fp);
        }
        else {
            $weatherFile = @file_get_contents($kernelDir . '/cache/api/' . $this->latitude . ',' . $this->longitude . ',' . $unixTimestamp);
        }

        $this->weatherData['time'][$normal] = @json_decode($weatherFile, true);
    }

    return $this->weatherData;
}
4

0 回答 0