使用memcache緩存來替代文件緩存,畢竟memcache緩存在內存, 文件緩存在硬盤(要看I/O的性能),一般來說內存的性能大于硬盤,所以一般來說memcache緩存優于文件緩存。

memcache相對于文件緩存的優點:
1、讀寫性能優異,特別是高并發時和文件緩存比有明顯優勢。
2、memcached組建支持集群,并且是自動管理負載均衡

注意:memcache的原理是內存分塊,單個item大于1M的數據存memcache和讀取速度可能有點慢。

1、首先添加memcache類文件mcache.php,放在include/lib文件夾下,服務器地址和端口地址在該文件中,請你自己配置。

 
 * @date 2014.5.25
 *
 */
class MCache{
 private static $_instance;
 private static $_connect_type = '';
 private $_memcache;
 
 /**
  * 私有化構造函數,禁止使用關鍵字new來實例Mcache類
  */
 private function __construct() {
  if (!class_exists('Memcache')) {
   throw new Exception('Class Memcache not exists');
  } 
  $conn = self::$_connect_type;
  $this->_memcache = new Memcache();
  $this->_memcache->$conn('localhost', '11211');
 }
 
 /**
  * 克隆私有化,禁止克隆實例
  */
 private function __clone() {}
 
 /**
  * 類入口,通過此靜態方法對類進行實例化
  */
 public static function getInstance($type = 'connect'){
  self::$_connect_type = ($type == 'connect') ? $type : 'pconnect';
  if (!self::$_instance instanceof self) {
   self::$_instance = new self();
  }
  return self::$_instance;
 }
 
 /**
  * 把數據添加到緩存
  * @param string $key 緩存的key
  * @param string|array|int... $value 緩存的數據
  * @param int $flag  使用zlib MEMCACHE_COMPRESSED
  * @param int $expire_time  緩存時間
  */
 public function set($key, $value,$flag = 0 ,$expire_time = 0){
   $this->_memcache->set($key, $value, $flag, $expire_time);   
 }

 /**
  * 替換緩存數據
  * @param string $key 緩存的key
  * @param string|array|int... $value 緩存的數據
  * @param int $flag  使用zlib MEMCACHE_COMPRESSED
  * @param int $expire_time  緩存時間
  */
 public function replace($key, $value,$flag = 0 , $expire_time = 0){
   $this->_memcache->replace($key, $value, $flag, $expire_time);   
 }
 
 /**
  * 從緩存讀取數據
  * @param string|array|int... $key
  */
 public function get($key){
  return $this->_memcache->get($key); 
 }
 
 /**
  * 從緩存刪除數據
  * @param string|array|int... $key
  */
 public function del($key,$expire_time = 0){
  $this->_memcache->delete($key, $expire_time);  
 }

 public function close(){
	return $this->_memcache->close(); 
 }
}

2、修改include/lib/cache.php,添加實例,第28行修改為

private function __construct() {
	$this->db = Database::getInstance();
	$this->memcache = MCache::getInstance();
}

3、修改include/lib/cache.php的讀寫memcache緩存,大概507行下面的cacheWrite和readCache函數修改為

	/**
	 * 寫入緩存
	 */
	function cacheWrite ($cacheData, $cacheName) {
		$this->memcache->set($cacheName,$cacheData);
	}

	/**
	 * 讀取緩存文件
	 */
	function readCache($cacheName) {
		if($this->memcache->get($cacheName)===false){call_user_func(array($this, 'mc_' . $cacheName));}
		$data = $this->memcache->get($cacheName);
		$this->{$cacheName.'_cache'} = unserialize($data);
		return $this->{$cacheName.'_cache'};
	}

內容來源于:http://www.myxzy.com/post-420.html

上一篇
2022-09-03

他跳槽了15次,靠這套秘籍,每次都能極速取得成功!

下一篇
2022-09-03

卸載阿里云服務器云盾(安騎士)功能