|
Cache是“以空間換時間”策略的典型應(yīng)用模式,是提高系統(tǒng)性能的一種重要方法。緩存的使用在大訪問量的情況下能夠極大的減少對數(shù)據(jù)庫操作的次數(shù),明顯降低系統(tǒng)負(fù)荷提高系統(tǒng)性能。相比頁面的緩存,結(jié)果集是一種“原始數(shù)據(jù)”不包含格式信息,數(shù)據(jù)量相對較小,而且可以再進行格式化,所以顯得相當(dāng)靈活。由于php是“一邊編譯一邊執(zhí)行”的腳本語言,某種程度上也提供了一種相當(dāng)方便的結(jié)果集緩存使用方法――通過動態(tài)include相應(yīng)的數(shù)據(jù)定義代碼段的方式使用緩存。如果在“RamDisk”上建緩存的話,效率應(yīng)該還可以得到進一步的提升。以下是一小段示例代碼,供參考。
<?
// load data with cache
function load_data($id,$cache_lifetime) {
// the return data
$data = array();
// make cache filename
$cache_filename = ‘cache_‘.$id.‘.php‘;
// check cache file‘s last modify time
$cache_filetime = filemtime($cache_filename);
if (time() - $cache_filetime <= $cache_lifetime) {
//** the cache is not expire
include($cache_filename);
} else {
//** the cache is expired
// load data from database
// ...
while ($dbo->nextRecord()) {
// $data[] = ...
}
// format the data as a php file
$data_cache = "
while (list($key, $val) = each($data)) {
$data_cache .= "$data[‘$key‘]=array(‘";
$data_cache .= "‘NAME‘=>"".qoute($val[‘NAME‘])."/","
$data_cache .= "‘VALUE‘=>/"".qoute($val[‘VALUE‘])."/""
$data_cache .= ";);/r/n";
}
$data_cache = "?>/r/n";
// save the data to the cache file
if ($fd = fopen($cache_filename,‘w+‘)) {
fputs($fd,$data_cache);
fclose($fd);
}
}
return $data;
}
?>
適用情況:
1.數(shù)據(jù)相對比較穩(wěn)定,主要是讀取操作。
2.文件操作要比數(shù)據(jù)庫操作快。
3.復(fù)雜數(shù)據(jù)訪問,大數(shù)據(jù)量訪問,密集數(shù)據(jù)訪問,系統(tǒng)數(shù)據(jù)庫負(fù)載極重。
4.Web/DB分離結(jié)構(gòu)或者多Web單DB結(jié)構(gòu)。
未經(jīng)證實的問題:
1.并發(fā)訪問時對文件的讀寫是否會引起鎖定問題。
2.涉及到的數(shù)據(jù)文件太多時,性能如何。
擴展思路:
1.生成JavaScript數(shù)據(jù)定義代碼,在客戶端調(diào)用。
2.還未想到……
望共同探討。
php技術(shù):PHP數(shù)據(jù)緩存技術(shù),轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。