HACK emlog程序教程,操作前请先备份。使用Redis缓存来替代文件缓存,毕竟Redis缓存在内存, 文件缓存在硬盘(要看I/O的性能),一般来说内存的性能大于硬盘,所以一般来说Redis缓存优于文件缓存。
Redis相对于文件缓存的优点:
1、读写性能优异,特别是高并发时和文件缓存比有明显优势。
2、Redis支持集群。
修改include/lib/cache.php文件
1、变量 private $db; 改为 private $db; private $redis; 2、修改构造函数 protected function __construct() { $this->db = Database::getInstance(); } 改为 protected function __construct() { $this->db = Database::getInstance(); $this->redis = new redis(); $this->redis->connect('127.0.0.1','6379'); } 3、修改缓存写入函数 public function cacheWrite($cacheData, $cacheName) { $cachefile = EMLOG_ROOT . '/content/cache/' . $cacheName . '.php'; $cacheData = "<?php exit;//" . $cacheData; @ $fp = fopen($cachefile, 'wb') or emMsg('读取缓存失败'); @ fwrite($fp, $cacheData) or emMsg('写入缓存失败,缓存目录 (content/cache) 不可写'); $this->{$cacheName . '_cache'} = null; fclose($fp); } 改为 public function cacheWrite($cacheData, $cacheName) { $this->redis->set($cacheName, $cacheData); } 4、修改缓存读取函数 public function readCache($cacheName) { if ($this->{$cacheName . '_cache'} != null) { return $this->{$cacheName . '_cache'}; } else { $cachefile = EMLOG_ROOT . '/content/cache/' . $cacheName . '.php'; // 如果缓存文件不存在则自动生成缓存文件 if (!is_file($cachefile) || filesize($cachefile) <= 0) { if (method_exists($this, 'mc_' . $cacheName)) { call_user_func(array($this, 'mc_' . $cacheName)); } } if ($fp = fopen($cachefile, 'r')) { $data = fread($fp, filesize($cachefile)); fclose($fp); clearstatcache(); $this->{$cacheName . '_cache'} = unserialize(str_replace("<?php exit;//", '', $data)); return $this->{$cacheName . '_cache'}; } } } 改为 public function readCache($cacheName) { if($this->redis->get($cacheName)===false){ call_user_func(array($this, 'mc_' . $cacheName)); } return unserialize($this->redis->get($cacheName)); }
到此修改已经完毕,到后台刷新缓存即可,如有什么问题可以留言评论。
卸载方法:如果不想用Redis缓存了,就用原版的cache.php替换掉修改的cache.php即可。
目前有 2 条评论
wangyetao 2023-12-07 15:471楼
楼主$this->redis->connet(\'127.0.0.1\',\'6379\');你文章的连接数据库的connet写错了,应该是$this->redis->connect(\'127.0.0.1\',\'6379\');评论
星之宇 2023-12-07 16:40
谢谢指出,已修正。回复