// 自定義緩存類
class Cache_Filesystem {
// 緩存寫保存
function set ($key, $data, $ttl) {
//打開文件為讀/寫模式
$h = fopen($this->get_filename($key), ‘a+‘);
if (!$h) throw new Exception("Could not write to cache");
flock($h, LOCK_EX); //寫鎖定,在完成之前文件關閉不可再寫入
fseek($h, 0); // 讀到文件頭
ftruncate($h, 0); //清空文件內容
// 根據生存周期$ttl寫入到期時間
$data = serialize(array(time()+$ttl, $data));
if (fwrite($h, $data) === false) {
throw new Exception(‘Could not write to cache‘);
}
fclose($h);
}
// 讀取緩存數據,如果未取出返回失敗信息
function get ($key) {
$filename = $this->get_filename($key);
if ( !file_exists( $filename ) ) {
return false;
}
$h = fopen($filename, ‘r‘);
if (!$h) return false;
// 文件讀取鎖定
flock($h, LOCK_SH);
$data = file_get_contents($filename);
fclose($h);
$data = @unserialize($data);
if ( !$data ) {
// 如果反序列化失敗,則徹底刪除該文件
unlink($filename);
return false;
}
if (time() > $data[0]) {
// 如果緩存已經過期,則刪除文件
unlink($filename);
return false;
}
}
// 清除緩存
function clear ( $key ) {
$filename = $this->get_filename($key);
if (file_exists($filename)) {
return unlink($filename);
} else {
return false;
}
}
// 獲取緩存文件
private function get_filename ($key) {
return ‘./cache/‘ . md5($key);
}
}
調用
require ‘./4.3-cache_class.php‘;
// 創建新對象
$cache = new Cache_Filesystem();
function getUsers () {
global $cache;
// 自定義一個緩存key唯一標識
$key = ‘getUsers:selectAll‘;
// 檢測數據是否緩存
if ( !$data = $cache->get( $key ) ) {
// 如果沒有緩存,則獲取新數據
$db_host = ‘localhost‘;
$db_user = ‘root‘;
$db_password = ‘root‘;
$database = ‘ecshop_test‘;
$conn = mysql_connect( $db_host, $db_user, $db_password);
mysql_select_db($database);
//執行sql查詢
$result = mysql_query("select * from ecs_users");
$data = array();
// 將獲取到的數據放入數組$data中
while ( $row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
// 保存該數據到緩存中,生存周期為10分鐘
$cache->set($key, $data, 10);
}
return $data;
}
try {
$users = getUsers();
print_r($users);
$key = ‘getUsers:selectAll‘;
//$cache->clear($key);
} catch (Exception $e) {
print $e->getMessage();
}
原文:http://www.cnblogs.com/chengzhi59/p/7419523.html