說,近期接手的論壇專案,因為對于代碼,不是特別熟悉,有個地方需要用到快取,所以寫了一個基于file_put_contents函式檔案的寫入和fopen函式檔案的打開,實作的一個檔案快取,具體可以用,但是對于高并發,多用戶同時訪問,不知道會如何,
如果有大佬看見這篇博客,希望給些意見或評論,主要是,phpwind這個論壇的快取確實不太熟悉,自己寫的快取這個,其實就是一個檔案讀寫而已,正真的快取,希望大佬們給個大致的說道,
下面是代碼正文:
<?php /** * 生成一個檔案快取 * User:WuYan * Time:2020.5.12 */ class cache { const CACHE_PATH = './data/file/';//快取路徑 const CACHE_TYPE = '.md';//快取檔案后綴 //創建靜態私有的變數保存該類物件 static private $instance; //防止使用new直接創建物件 private function __construct(){} //防止使用clone克隆物件 private function __clone(){} static public function getInstance() { //判斷$instance是否是Singleton的物件,不是則創建 if (!self::$instance instanceof self) { self::$instance = new self(); } return self::$instance; } /** * 設定檔案快取 * @param [type] $key 快取鍵名 string * @param [type] $value 快取鍵值 array * @param integer $time 快取時間 s * @return [booleans] */ public static function setCache($key, $value, $time = 0) { if (!is_array($value)) { return false; } //創建快取目錄 if (!file_exists(self::CACHE_PATH)) { $mode = intval('0777', 8); mkdir(self::CACHE_PATH, $mode, true); } $data = [ 'time' => $time ? time() + $time : 0, 'data' => $value, ]; //寫入檔案,重寫模式 $result = file_put_contents(self::CACHE_PATH.'/'.$key.self::CACHE_TYPE, json_encode($data)); if ($result) { return true; } else { return false; } } /** * 讀取快取檔案內容 * @param [type] $key 快取鍵名 string * @return [array] */ public static function getCache($key) { //檔案路徑 $file_path = self::CACHE_PATH.$key.self::CACHE_TYPE; if (file_exists($file_path)) { //打開檔案 $fp = fopen($file_path,"r"); //指定讀取大小,這里把整個檔案內容讀取出來 $string = fread($fp,filesize($file_path)); if (!$string) { return false; } $array = json_decode($string, true); if (empty($array['data'])) { return false; } //判斷是否過期 if ($array['time']) { if ($array['time'] > time()) {//未過期 $result_data = $array['data']; } else { //關閉檔案并洗掉 fclose($fp); unlink($file_path); return false; } } else {//未設定時效 $result_data = $array['data']; } //關閉檔案 fclose($fp); return $result_data; } else { return false; } } }
呼叫的話,直接
cache::setCache('pw_area',['100'=>'北京市','101'=>'上海市'],3600);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/10265.html
標籤:其他
上一篇:優秀的程式員真的不寫注釋嗎?
下一篇:2020-5-15 第一期
