Php+redis Cache Class
<?php class Rediscache {/** * $host: Redis server IP * $port: Redis Server port * $lifetime: Cache file validity, in seconds * $CAC Heid: Cache file path, including file name */private $host; Private $port; Private $lifetime; Private $cacheid; Private $data; Public $redis; /** * destructor, check if cache directory is valid, default assignment */function __construct ($lifetime =1800) {//config $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); }/** * Check that the cache is valid */Private function IsValid () {$data = $this->data; if (! $data [' content ']) return false; if (Time ()-$data [' Creattime '] > $this->lifetime) return false; REturn true; }/** * Write cache * $mode = = 0, get page content in browser cache */Public function write ($mode =0, $content = ") {switch ($mod e) {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 (' Write cache failed! '); }}/** * Load Cache * EXIT () load cache to terminate the execution of the original page program, cache invalid run the original page program generate cache * Ob_start () Open browser cache to get page content at the end of the page * * Public fun Ction Load () {if ($this->isvalid ()) {echo $this->data[' content ']; Exit (); } else {Ob_start (); }}/** * Clear cache */Public function clean () {try {$this->redis->hdel ($this->cacheid, a Rray (' ContenT ', ' creattime ')); } catch (Exception $e) {$this->error (' Purge cache failed! '); }}/** * Get the cache file path */Private Function Getcacheid () {return $this->dir.md5 ($this->geturl ()). $this- >ext; }/** * Gets the current page full 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; }/** * Output error message */Private Function error ($STR) {echo ' <div style= "color:red;" > '. $str. ' </div> '; }}//Usage://require_once (' rediscache.php ');//$cache = new Rediscache (10); Set the cache lifetime//if ($_get[' ClearCache ']) $cache->clean ();/Else $cache->load (); Load cache, cache valid then do not execute the following page code////page code start///page code end//$cache->write (); First run or cache expiration, generate cache?>
Php+redis Cache Class