Redis是一个高级的key-value存储系统,类似memcached,所有内容都存在内存中,因此每秒钟可以超过10万次GET操作。
我下面提出的解决方案是在Redis中缓存所有输出的HTML 内容而无需再让WordPress重复执行页面脚本。这里使用Redis代替Varnish设置简单,而且可能更快。
<strong>1、安装Redis</strong>
如果你使用的是 Debian 或者衍生的操作系统可使用如下命令安装 Redis:
apt-get install redis-server
<span style="white-space:nowrap;">或者阅读<a href="http://redis.io/download" target="_blank" rel="noopener"> 安装指南</a></span><a href="http://redis.io/download" target="_blank" rel="noopener"></a>
<strong>2、使用 Predis 作为 Redis 的 PHP 客户端 </strong>
你需要一个客户端开发包以便 PHP 可以连接到 Redis 服务上。
这里我们推荐 Predis, 上传 predis.php 到 WordPress 的根目录。
前端缓存的PHP脚本
步骤1:在WordPress 的根目录创建新文件 index-with-redis.php ,内容如下:
del($redis_key); // Second case: cache exist in redis, let's display it } else if ($redis->exists($redis_key)) { $html_of_current_page = $redis->get($redis_key); echo $html_of_current_page; echo ""; // third: a normal visitor without cache. And do not cache a preview page from the wp-admin: } else if ($_SERVER['REMOTE_ADDR'] != $ip_of_this_website && strstr($current_page_url, 'preview=true') == false) { require('./wp-blog-header.php'); $html_of_current_page = file_get_contents($current_page_url); $redis->setex($redis_key, $seconds_of_caching, $html_of_current_page); echo ""; // last case: the normal WordPress. Should only be called with file_get_contents: } else { require('./wp-blog-header.php'); } // Let's display some page generation time (note: CloudFlare may strip out comments): $end = microtime(); $t2 = (getmicrotime($end) - getmicrotime($start)); if ($_SERVER['REMOTE_ADDR'] != $ip_of_this_website) { echo ""; } ?>
或者直接下载<a href="https://raw.github.com/gist/3053250/c97aa5070a1b6e237428c260b3abe4ae0a59df8e/index-with-redis.php" target="_blank" rel="noopener"> index-with-redis.php</a>
步骤2:将上述代码中的 IP 地址替换成你网站的 IP 地址
步骤3:在.htaccess 中将所有出现 index.php 的地方改为 index-with-redis.php ,如果你使用的是 Nginx 则修改 nginx.conf 中的 index.php 为 index-with-redis.php(并重载 Nginx : killall -s HUP nginx)。
<strong>3、性能测试</strong>
1.没有Redis 的情况下,平均首页执行1.614 秒,文章页0.174 秒(无任何缓存插件) 。
2.使用Redis 的情况下,平均页面执行时间0.00256秒
我已经在我的博客中使用了如上的方法进行加速很长时间了,一切运行良好。
<strong>4、建议</strong><strong> </strong>
我的环境是Nginx + PHP-FPM + APC + Cloudflare + Redis. 安装在一个 nano VPS 中,无缓存插件。
请确认使用了gzip压缩,可加快访问速度。
访问 wp-admin
要访问 wp-admin 必须使用 /wp-admin/index.php 代替原来的 /wp-admin/。
注:以上内容摘自于互联网。