原文 http://www.oschina.net/question/12_60107
Redis 是一个高级的 key-value 存储系统,类似 memcached,所有内容都存在内存中,因此每秒钟可以超过 10 万次 GET 操作。
我下面提出的解决方案是在 Redis 中缓存所有输出的 HTML 内容而无需再让 WordPress 重复执行页面脚本。这里使用 Redis 代替 Varnish 设置简单,而且可能更快。
安装 Redis
如果你使用的是 Debian 或者衍生的操作系统可使用如下命令安装 Redis:
1 | apt-get install redis-server |
或者阅读 安装指南
使用 Predis 作为 Redis 的 PHP 客户端
你需要一个客户端开发包以便 PHP 可以连接到 Redis 服务上。
这里我们推荐 Predis. 上传 predis.php 到 WordPress 的根目录。
前端缓存的 PHP 脚本
步骤1: 在 WordPress 的根目录创建新文件 index-with-redis.php ,内容如下:
005 | $seconds_of_caching = 60*60*24*7; |
007 | $ip_of_this_website = '204.62.14.112' ; |
031 | if (isset( $_SERVER [ 'HTTP_CF_CONNECTING_IP' ])) { |
033 | $_SERVER [ 'REMOTE_ADDR' ] = $_SERVER [ 'HTTP_CF_CONNECTING_IP' ]; |
041 | define( 'WP_USE_THEMES' , true); |
047 | function getmicrotime( $t ) { |
049 | list( $usec , $sec ) = explode ( " " , $t ); |
051 | return ((float) $usec + (float) $sec ); |
055 | $start = microtime(); |
061 | include ( "predis.php" ); |
063 | $redis = new Predis\Client( '' ); |
069 | $current_page_url = "http://" . $_SERVER [ 'HTTP_HOST' ]. $_SERVER [ 'REQUEST_URI' ]; |
071 | $current_page_url = str_replace ( '?refresh=yes' , '' , $current_page_url ); |
073 | $redis_key = md5( $current_page_url ); |
079 | if (isset( $_GET [ 'refresh' ]) || substr ( $_SERVER [ 'REQUEST_URI' ], -12) == '?refresh=yes' || ( $_SERVER [ 'HTTP_REFERER' ] == $current_page_url && $_SERVER [ 'REQUEST_URI' ] != '/' && $_SERVER [ 'REMOTE_ADDR' ] != $ip_of_this_website )) { |
081 | require ( './wp-blog-header.php' ); |
083 | $redis ->del( $redis_key ); |
089 | } else if ( $redis ->exists( $redis_key )) { |
091 | $html_of_current_page = $redis ->get( $redis_key ); |
093 | echo $html_of_current_page ; |
095 | echo "<!-- This is cache -->" ; |
101 | } else if ( $_SERVER [ 'REMOTE_ADDR' ] != $ip_of_this_website && strstr ( $current_page_url , 'preview=true' ) == false) { |
103 | require ( './wp-blog-header.php' ); |
105 | $html_of_current_page = file_get_contents ( $current_page_url ); |
107 | $redis ->setex( $redis_key , $seconds_of_caching , $html_of_current_page ); |
109 | echo "<!-- Cache has been set -->" ; |
117 | require ( './wp-blog-header.php' ); |
129 | $t2 = (getmicrotime( $end ) - getmicrotime( $start )); |
131 | if ( $_SERVER [ 'REMOTE_ADDR' ] != $ip_of_this_website ) { |
133 | echo "<!-- Cache system by Jim Westergren. Page generated in " . round ( $t2 ,5). " seconds. -->" ; |
或者直接下载 index-with-redis.php
步骤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)。
性能测试
- 没有 Redis 的情况下,平均首页执行 1.614 秒,文章页 0.174 秒(无任何缓存插件)
- 使用 Redis 的情况下,平均页面执行时间 0.00256 秒
我已经在我的博客中使用了如上的方法进行加速很长时间了,一切运行良好。
其他建议
我的环境是 Nginx + PHP-FPM + APC + Cloudflare + Redis. 安装在一个 nano VPS 中,无缓存插件。
请确认使用了 gzip 压缩,可加快访问速度。
访问 wp-admin
要访问 wp-admin 必须使用 /wp-admin/index.php 代替原来的 /wp-admin/.
英文原文,OSCHINA原创翻译