簡體   English   中英

如何實現Yahoo貨幣緩存?

[英]How to implement a Yahoo currency cache?

我的網站上有Yahoo貨幣腳本,但是它們花費了太多時間來加載,並降低了我的網站速度。 如何緩存它們並每3600分鍾刷新一次緩存?

您需要一些地方來存儲這些結果。 MySQL是一個流行的選擇,但是如果數據不需要保留或具有歷史值,則使用內存緩存會更容易。 根據您的主機,這兩個選項可能都可用。

這個想法是:

  • 創建某種緩存目錄並設置定義的緩存壽命
  • 然后,在函數開始時,檢查緩存
    • 如果存在,請檢查其年齡。
      • 如果在范圍內,得到它
    • 如果緩存太舊
      • 使用實時數據並將該數據設置到緩存文件中。

這樣的事情應該可以解決問題:

define(CACHE_DIR, 'E:/xampp/xampp/htdocs/tmp');
define(CACHE_AGE, 3600);
/**
 * Adds data to the cache, if the cache key doesn't aleady exist.
 * @param string $path the path to cache file (not dir)
 * @return false if there is no cache file or the cache file is older that CACHE_AGE. It return cache data if file exists and within CACHE_AGE 
 */
function get_cache_value($path){
    if(file_exists($path)){
        $now = time();
        $file_age = filemtime($path);
        if(($now - $file_age) < CACHE_AGE){
            return file_get_contents($path);
        } else {
            return false;
        }
    } else {
        return false;
    }
}

function set_cache_value($path, $value){
    return file_put_contents($path, $value);
}

function kv_euro () {
    $path = CACHE_DIR . '/euro.txt';

    $kveuro = get_cache_value($path);
    if(false !== $kveuro){
        echo "\nFROM CACHE\n";
        return round($kveuro, 2);
    } else {
        echo "\nFROM LIVE\n";
        $from   = 'EUR'; /*change it to your required currencies */
        $to     = 'ALL';
        $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
        $handle = @fopen($url, 'r');

        if ($handle) {
            $result = fgets($handle, 4096);
            fclose($handle);
        }
        $allData = explode(',',$result); /* Get all the contents to an array */
        $kveuro = $allData[1];
        set_cache_value($path, $kveuro);
        return $kveuro;
    }
}

另外,與其使用fgets逐行讀取文件,還不如使用fgets ,而且由於您沒有在操縱一行,所以應該考慮使用file_get_contents函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM