資料緩存是web開發中常用的一種性能優化方法。目前主要檔案緩存或者資料庫緩存兩種形式,資料庫緩存資料庫不是什麼不可能的事情,的确也是很好很重要的。我認為傳統資料庫主要是從業務層、子產品設計等方面來考慮的,而緩存資料庫主要是從實作層來設計的,主要是為了緩存常用的多表查詢之類的。這裡主要将的是檔案緩存,網上很多資料了,這裡我轉載了一些原理資料。
Cache是“以空間換時間”政策的典型應用模式,是提高系統性能的一種重要方法。緩存的使用在大通路量的情況下能夠極大的減少對資料庫操作的次數,明顯降低系統負荷提高系統性能。相比頁面的緩存,結果集是一種“原始資料”不包含格式資訊,資料量相對較小,而且可以再進行格式化,是以顯得相當靈活。由于PHP是“一邊編譯一邊執行”的腳本語言,某種程度上也提供了一種相當友善的結果集緩存使用方法——通過動态include相應的資料定義代碼段的方式使用緩存。如果在“RamDisk”上建緩存的話,效率應該還可以得到進一步的提升。以下是一小段示例代碼,供參考。
1
function load_data($id,$cache_lifetime) {
2
3
// the return data
4
5
$data = array();
6
7
// make cache filename
8
9
$cache_filename = ‘cache_‘.$id.‘.php‘;
10
11
// check cache file‘s last modify time
12
13
$cache_filetime = filemtime($cache_filename);
14
15
if (time() - $cache_filetime <= $cache_lifetime) {
16
17
//** the cache is not expire
18
19
include($cache_filename);
20
21
} else {
22
23
//** the cache is expired
24
25
// load data from database
26
27
//
28
29
while ($dbo->nextRecord()) {
30
31
// $data[] =
32
33
}
34
35
// format the data as a php file
36
37
$data_cache = "
38
39
while (list($key, $val) = each($data)) {
40
41
$data_cache .= "$data[‘$key‘]=array(‘";
42
43
$data_cache .= "‘NAME‘=>"".qoute($val[‘NAME‘])."\","
44
45
$data_cache .= "‘VALUE‘=>\"".qoute($val[‘VALUE‘])."\""
46
47
$data_cache .= ";);";
48
49
50
51
$data_cache = "?>";
52
53
// save the data to the cache file
54
55
if ($fd = fopen($cache_filename,‘w+‘)) {
56
57
fputs($fd,$data_cache);
58
59
fclose($fd);
60
61
62
63
64
65
return $data;
66
67
68
69
?>
适用情況:
1.資料相對比較穩定,主要是讀取操作。
2.檔案操作要比資料庫操作快。
3.複雜資料通路,大資料量通路,密集資料通路,系統資料庫負載極重。
4.Web/DB分離結構或者多Web單DB結構。
////////////補充
<?php
function cache_isvalid($cacheid,$expire=300) {
@clearstatcache();
if (!@file_exists($cacheid)) return false;
if (!($mtime=@filemtime($cacheid))) return false;
$nowtime=mktime();
if (($mtime+$expire)<$nowtime) {
return false;
}else{
return true;
function cache_write($cacheid,$cachecontent) {
$retry=100;
for ($i=0;$i<$retry;$i++) {
$ft=@fopen($cacheid,"wb");
if ($ft!=false) break;
if ($i==($retry-1)) return false;
@flock($ft,LOCK_UN);
@flock($ft,LOCK_EX|LOCK_NB);
$tmp=@fwrite($ft,$cachecontent);
if ($tmp!=false) break;
@fclose($ft);
@chmod($cacheid,0777);
function cache_fetch($cacheid) {
$ft=@fopen($cacheid,"rb");
$cachecontent='';
while (!@feof($ft)) {
$cachecontent.=@fread($ft,4096);
return $cachecontent;
function cache_clear_expired($cachedirname,$expire=300) {
$cachedir=@opendir($cachedirname);
while (false!==($userfile=@readdir($cachedir))) {
if ($userfile!="." and $userfile!=".." and substr($userfile,-4,4)=='.htm') {
$cacheid=$cachedirname.'/'.$userfile;
if (!cache_isvalid($cacheid,$expire)) @unlink($cacheid);
@closedir($cachedir);
?>