使用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





















