您好,登錄后才能下訂單哦!
這篇文章給大家介紹怎么在php項(xiàng)目中自定義一個redis緩存類,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
php+redis緩存類
<?php class redisCache { /** * $host : redis服務(wù)器ip * $port : redis服務(wù)器端口 * $lifetime : 緩存文件有效期,單位為秒 * $cacheid : 緩存文件路徑,包含文件名 */ private $host; private $port; private $lifetime; private $cacheid; private $data; public $redis; /** * 析構(gòu)函數(shù),檢查緩存目錄是否有效,默認(rèn)賦值 */ function __construct($lifetime=1800) { //配置 $this->host = "127.0.0.1"; $this->port = "6379"; $redis = new Redis(); $redis->pconnect($this->host,$this->port); $this->redis=$redis; $this->cacheid = $this->getcacheid(); $this->lifetime = $lifetime; $this->data=$redis->hMGet($this->cacheid, array('content','creattime')); //print_r($this->redis); //print_r($this->data); } /** * 檢查緩存是否有效 */ private function isvalid(){ $data=$this->data; if (!$data['content']) return false; if (time() - $data['creattime'] > $this->lifetime) return false; return true; } /** * 寫入緩存 * $mode == 0 , 以瀏覽器緩存的方式取得頁面內(nèi)容 */ public function write($mode=0,$content='') { switch ($mode) { case 0: $content = ob_get_contents(); break; default: break; } ob_end_flush(); try { $this->redis->hMset($this->cacheid, array('content'=>$content,'creattime'=>time())); $this->redis->expireAt($this->cacheid, time() + $this->lifetime); } catch (Exception $e) { $this->error('寫入緩存失敗!'); } } /** * 加載緩存 * exit() 載入緩存后終止原頁面程序的執(zhí)行,緩存無效則運(yùn)行原頁面程序生成緩存 * ob_start() 開啟瀏覽器緩存用于在頁面結(jié)尾處取得頁面內(nèi)容 */ public function load() { if ($this->isvalid()) { echo $this->data['content']; exit(); } else { ob_start(); } } /** * 清除緩存 */ public function clean() { try { $this->redis->hDel($this->cacheid, array('content','creattime')); } catch (Exception $e) { $this->error('清除緩存失敗!'); } } /** * 取得緩存文件路徑 */ private function getcacheid() { return $this->dir.md5($this->geturl()).$this->ext; } /** * 取得當(dāng)前頁面完整url */ private function geturl() { $url = ''; if (isset($_SERVER['REQUEST_URI'])) { $url = $_SERVER['REQUEST_URI']; } else { $url = $_SERVER['Php_SELF']; $url .= empty($_SERVER['QUERY_STRING'])?'':'?'.$_SERVER['QUERY_STRING']; } return $url; } /** * 輸出錯誤信息 */ private function error($str) { echo '<div >'.$str.'</div>'; } } //用法: // require_once('redisCache.php'); // $cache = new redisCache(10); //設(shè)置緩存生存期 // if ($_GET['clearCache']) $cache->clean(); // else $cache->load(); //裝載緩存,緩存有效則不執(zhí)行以下頁面代碼 // //頁面代碼開始 // //頁面代碼結(jié)束 // $cache->write(); //首次運(yùn)行或緩存過期,生成緩存 ?>
關(guān)于怎么在php項(xiàng)目中自定義一個redis緩存類就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。