在web开发中,可以通过文件缓存,大大缓解数据库的压力。 如下代码是php中使用文件缓存的例子。
cachelayer.php
root = $_server[document_root].$root; $this->key = $key; } public function expired($life_span){ $this->life = $life_span; $file = $this->root./.$this->key..cachelayer; if(is_file($file)){ $mtime = filemtime($file); return (time() >= ($mtime + $this->life)); }else{ return true; } } public function put($content){ $file = $this->root./.$this->key..cachelayer; if(!is_dir(dirname($this->root))){ return false; } $this->delete(); $content = json_encode($content); return (bool)file_put_contents($file, $content); } public function get(){ $file = $this->root./.$this->key..cachelayer; if(is_file($file)){ return json_decode(file_get_contents($file), true); } return array(); } public function delete(){ $file = $this->root./.$this->key..cachelayer; if(is_file($file)){ unlink($file); return true; } return false; }}
复制代码
example.php
expired(60 * 10)){ echo cache doesn't exist or is expired. rebuilding...
; // if the cache is expired rebuild it $result = mysql_query(select id, title from navigation); $new_cache = array(); while($row = mysql_fetch_assoc($result)){ $new_cache[] = $row; } // save the array into the cache $cl_nav->put($new_cache);}echo loading from cache...
;// get the cache$cache = $cl_nav->get();// display the cacheforeach($cache as $row){ $id = $row[id]; $title = $row[title]; echo $title
;}
复制代码
php