美工统筹SEO,为企业电子商务营销助力!
php完成的redis缓存类界说与利用体例示例
一佰互联网站开辟设想(www.taishanly.com) 宣布日期 2020-04-26 09:01:52 阅读数: 134
本文实例报告了php完成的redis缓存类界说与利用体例。分享给大师供大师参考,详细以下:
php+redis缓存类
<?phpclass redisCache { /** * $host : redis办事器ip * $port : redis办事器端口 * $lifetime : 缓存文件有用期,单元为秒 * $cacheid : 缓存文件途径,包罗文件名 */ private $host; private $port; private $lifetime; private $cacheid; private $data; public $redis; /** * 析构函数,查抄缓存目次是不是有用,默许赋值 */ 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 , 以阅读器缓存的体例获得页面内容 */ 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() 载入缓存后停止原页面法式的履行,缓存有用则运转原页面法式天生缓存 * ob_start() 开启阅读器缓存用于在页面开头处获得页面内容 */ 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; } /** * 获得以后页面完全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 style="color:red;">".$str."</div>"; }}//用法:// require_once("redisCache.php");// $cache = new redisCache(10); //设置缓存保存期// if ($_GET["clearCache"]) $cache->clean();// else $cache->load(); //装载缓存,缓存有用则不履行以下页面代码// //页面代码起头// //页面代码竣事// $cache->write(); //初次运转或缓存过时,天生缓存?>
更多对于PHP相干内容感乐趣的读者可检查本站专题:《php+redis数据库法式设想技能总结》、《php面向工具法式设想入门教程》、《PHP根基语法入门教程》、《PHP数组(Array)操纵技能大全》、《php字符串(string)用法总结》、《php+mysql数据库操纵入门教程》及《php罕见数据库操纵技能汇总》
但愿本文所述对大师PHP法式设想有所赞助。
上一篇: PHP完成将标点标记正则替代为空格的体例 | 下一篇:PHP编程完成剧本异步履行的体例