用Redis缓存来给WordPress站点加速-适用于Apache和Nginx

Redis-Wordpress_001

Redis是一个开源、支持网络、基于内存的key-value存储系统,类似memcached,性能极高,支持超过100K+ 每秒的读写频率,一些大型的网站例如ITeye(JavaEye)和CSDN现在都用到了Redis。

与memcached相比,Redis提供了持久化存储,重启了服务器后memcached需要重新创建缓存,而Redis依赖快照进行持久化,即使服务器刚开机启动也不会导致负载陡增。Redis缓存比较适合大流量的Wordpress。

当你的WordPress中的文章达到上万篇,随着流量的增加,Wordpress的服务器压力也随之不断加大,Wordpress发布文章和后台相关的操作都会变得缓慢,这时如果单从硬件上投入来提高Wordpress性能显然不划算。

利用Redis将WordPress页面直接缓存在服务器的内存中,这样在避免了PHP重复执行操作的同时,内存的极速响应能够最大限度地提升Wordpress页面的访问速度,部落实际测试发现页面执行时间可以降低到0.00X秒级别,比没有使用Redis缓存提升几倍甚至十几倍以上。

用Redis缓存来给WordPress站点加速-适用于Apache和Nginx

一、 在VPS或者服务器上安装Redis

1、而对于一般的VPS,我们可以直接用以下命令安装(注意:redis-2.8.9是当前稳定版本,大家可以及时关注官网获得最新的:http://redis.io/download):


wget http://download.redis.io/releases/redis-2.8.9.tar.gz
tar xzf redis-2.8.9.tar.gz
cd redis-2.8.9
make

Redis-Wordpress_011

2、Redis会在src目录下生成几个可执行文件如:redis-benchmark,redis-check-aof,redis-check-dump,redis-cli,redis-sentinel,redis-server。执行:src/redis-server或者service redis-server start就是启动Redis。

3、配置开机启动Redis,执行以下命令:vi /etc/rc.d/rc.local,加入redis-server路径,例如:/src/redis-server

4、在VPS上和服务器上安装并运行Redis了后,可以在phpinfo看到。

Redis-Wordpress_051

二、用Predis.php作为Redis的PHP客户端

1、我们可以使用Predis.php来作为PHP客户端,直接将Predis.php下载并上传到Wordpress的根目录下,CD到Wordpress根目录,执行以下命令:


wget http://uploads.staticjw.com/ji/jim/predis.php
chown www.www ./predis.php

2、这是Predis.php的备份下载:Predis.php下载。你可以手动下载并上传。

Redis-Wordpress_061

三、安装Redis前端缓存的PHP脚本

1、Redis前端缓存的PHP脚本来自:http://www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/

<?php

/*
    Author: Jim Westergren & Jeedo Aquino
    File: index-with-redis.php
    Updated: 2012-10-25

    This is a redis caching system for wordpress.
    see more here: www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/

    Originally written by Jim Westergren but improved by Jeedo Aquino.

    some caching mechanics are different from jim's script which is summarized below:

    - cached pages do not expire not unless explicitly deleted or reset
    - appending a ?c=y to a url deletes the entire cache of the domain, only works when you are logged in
    - appending a ?r=y to a url deletes the cache of that url
    - submitting a comment deletes the cache of that page
    - refreshing (f5) a page deletes the cache of that page
    - includes a debug mode, stats are displayed at the bottom most part after </html>

    for setup and configuration see more here:

    www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/

    use this script at your own risk. i currently use this albeit a slightly modified version
    to display a redis badge whenever a cache is displayed.

*/

// change vars here
$cf = 1;            // set to 1 if you are using cloudflare
$debug = 0;            // set to 1 if you wish to see execution time and cache actions
$display_powered_by_redis = 1;  // set to 1 if you want to display a powered by redis message with execution time, see below

$start = microtime();   // start timing page exec

// if cloudflare is enabled
if ($cf) {
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
}

// from wp
define('WP_USE_THEMES', true);

// init predis
include("predis.php");
$redis = new Predis\Client('');

// init vars
$domain = $_SERVER['HTTP_HOST'];
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = str_replace('?r=y', '', $url);
$url = str_replace('?c=y', '', $url);
$dkey = md5($domain);
$ukey = md5($url);

// check if page isn't a comment submission
(isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0') ? $submit = 1 : $submit = 0;

// check if logged in to wp
$cookie = var_export($_COOKIE, true);
$loggedin = preg_match("/wordpress_logged_in/", $cookie);

// check if a cache of the page exists
if ($redis->hexists($dkey, $ukey) && !$loggedin && !$submit && !strpos($url, '/feed/')) {

    echo $redis->hget($dkey, $ukey);
    $cached = 1;
    $msg = 'this is a cache';

// if a comment was submitted or clear page cache request was made delete cache of page
} else if ($submit || substr($_SERVER['REQUEST_URI'], -4) == '?r=y') {

    require('./wp-blog-header.php');
    $redis->hdel($dkey, $ukey);
    $msg = 'cache of page deleted';

// delete entire cache, works only if logged in
} else if ($loggedin && substr($_SERVER['REQUEST_URI'], -4) == '?c=y') {

    require('./wp-blog-header.php');
    if ($redis->exists($dkey)) {
        $redis->del($dkey);
        $msg = 'domain cache flushed';
    } else {
        $msg = 'no cache to flush';
    }

// if logged in don't cache anything
} else if ($loggedin) {

    require('./wp-blog-header.php');
    $msg = 'not cached';

// cache the page
} else {

    // turn on output buffering
    ob_start();

    require('./wp-blog-header.php');

    // get contents of output buffer
    $html = ob_get_contents();

    // clean output buffer
    ob_end_clean();
    echo $html;

    // Store to cache only if the page exist and is not a search result.
    if (!is_404() && !is_search()) {
        // store html contents to redis cache
        $redis->hset($dkey, $ukey, $html);
        $msg = 'cache is set';
    }
}

$end = microtime(); // get end execution time

// show messages if debug is enabled
if ($debug) {
    echo $msg.': ';
    echo t_exec($start, $end);
}

if ($cached && $display_powered_by_redis) {
    // You should move this CSS to your CSS file and change the: float:right;margin:20px 0;
    echo "<style>#redis_powered{float:right;margin:20px 0;background:url(http://images.staticjw.com/jim/3959/redis.png) 10px no-repeat #fff;border:1px solid #D7D8DF;padding:10px;width:190px;}
    #redis_powered div{width:190px;text-align:right;font:10px/11px arial,sans-serif;color:#000;}</style>";
    echo "<a href=\"http://www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/\" style=\"text-decoration:none;\"><div id=\"redis_powered\"><div>Page generated in<br/> ".t_exec($start, $end)." sec</div></div></a>";
}

// time diff
function t_exec($start, $end) {
    $t = (getmicrotime($end) - getmicrotime($start));
    return round($t,5);
}

// get time
function getmicrotime($t) {
    list($usec, $sec) = explode(" ",$t);
    return ((float)$usec + (float)$sec);
}

?>

 

2、 你也可以直接点击备用下载:index-with-redis.php下载地址。 Github项目:https://gist.github.com/JimWestergren/3053250#file-index-with-redis-php

3、 如果你正在使用cloudflare,请设置cf = 1; ,如果你想在页面上看到脚本执行时间和缓存加载时间,请设置$debug = 1; display_powered_by_redis = 1表示显示powered_by信息。

Redis-Wordpress_07

4、将index-with-redis.php上传到Wordpress的根目录,如果你使用的是nginx,重命令原来的index.php为任意其它名字,把index-with-redis.php重命名为index.php。

Redis-Wordpress_02

5、如果你使用的是Apache,则需要把.htaccess中出现的index.php替换成index-with-redis.php。

Redis-Wordpress_04

6、所有的操作完成后,你就可以刷新一下Wordpress页面,查看Redis缓存效果了。

7、实际使用过程中发现以上代码会出现Wordpress首页和分类没有及时缓存,这里再给出优化版本,出自http://www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/

8、功能差不多,主要有:登录时页面不缓存、除非删除或者重置否则不删除缓存页面、登录时在任意URL后加上?c=y可以删除整个网站缓存、在任意URL后面加上?c=y可以清除此URL缓存、allow_fopen被禁止也可以正常运行、发表评论时删除该页面缓存。

9、index-with-redis.php优化版本的源码是:


<?php

/*
    author: jeedo aquino
    file: wp-index-redis.php
    credit: jim westergren
    updated: 2012-10-23

    this is a redis caching system for wordpress inspired by jim westergren.
    see more here: www.jimwestergren.com/wordpress-with-redis-as-a-frontend-cache/
    some caching mechanics are different from jim's script which is summarized below:

    - cached pages do not expire not unless explicitly deleted or reset
    - appending a ?c=y to a url deletes the entire cache of the domain, only works when you are logged in
    - appending a ?r=y to a url deletes the cache of that url
    - script still works even if allow_fopen is disabled
    - submitting a comment deletes the cache of that page
    - refreshing (f5) a page deletes the cache of that page
    - includes a debug mode, stats are displayed at the bottom most part after 

    for setup and configuration see more here:

    www.jeedo.net/lightning-fast-wordpress-with-nginx-redis/

    use this script at your own risk. i currently use this albeit a slightly modified version
    to display a redis badge whenever a cache is displayed.

*/

// change vars here
$cf = 0;                // set to 1 if you are using cloudflare
$debug = 0;             // set to 1 if you wish to see execution time and cache actions

$start = microtime();   // start timing page exec

// if cloudflare is enabled
if ($cf) {
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
    }
}

// from wp
define('WP_USE_THEMES', true);

// init predis
include("predis.php");
$redis = new Predis\Client('');

// init vars
$domain = $_SERVER['HTTP_HOST'];
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$url = str_replace('?r=y', '', $url);
$url = str_replace('?c=y', '', $url);
$dkey = md5($domain);
$ukey = md5($url);

// check if page isn't a comment submission
(($_SERVER['HTTP_CACHE_CONTROL'] == 'max-age=0') ? $submit = 1 : $submit = 0);

// check if logged in to wp
$cookie = var_export($_COOKIE, true);
$loggedin = preg_match("/wordpress_logged_in/", $cookie);

// check if a cache of the page exists
if ($redis->hexists($dkey, $ukey) && !$loggedin && !$submit) {

    echo $redis->hget($dkey, $ukey);
    if (!$debug) exit(0);
    $msg = 'this is a cache';

// if a comment was submitted or clear page cache request was made delete cache of page
} else if ($submit || substr($_SERVER['REQUEST_URI'], -4) == '?r=y') {

    require('./wp-blog-header.php');
    $redis->hdel($dkey, $ukey);
    $msg = 'cache of page deleted';

// delete entire cache, works only if logged in
} else if ($loggedin && substr($_SERVER['REQUEST_URI'], -4) == '?c=y') {

    require('./wp-blog-header.php');
    if ($redis->exists($dkey)) {
        $redis->del($dkey);
        $msg = 'domain cache flushed';
    } else {
        $msg = 'no cache to flush';
    }

// if logged in don't cache anything
} else if ($loggedin) {

    require('./wp-blog-header.php');
    $msg = 'not cached';

// cache the page
} else {

    // turn on output buffering
    ob_start();

    require('./wp-blog-header.php');

    // get contents of output buffer
    $html = ob_get_contents();

    // clean output buffer
    ob_end_clean();
    echo $html;

    // store html contents to redis cache
    $redis->hset($dkey, $ukey, $html);
    $msg = 'cache is set';
}

$end = microtime(); // get end execution time

// show messages if debug is enabled
if ($debug) {
    echo $msg.': ';
    echo t_exec($start, $end);
}

// time diff
function t_exec($start, $end) {
    $t = (getmicrotime($end) - getmicrotime($start));
    return round($t,5);
}

// get time
function getmicrotime($t) {
    list($usec, $sec) = explode(" ",$t);
    return ((float)$usec + (float)$sec);
}

?>

 

四、Wordpress删除Redis页面缓存的方法

1、删除某一个页面的缓存:发表评论、按下F5刷新、在URL后面加上?r=y回车。

2、删除整站页面缓存:登录到Wordpress后台,在任意URL后面加上?r=y回车。

3、更新文章时自动刷新首页缓存:在你的Wordpress的Function.php中加入以下代码(出自:https://blog.zts1993.com/4738.html):

function newPostRefresh() {
$temp=file_get_contents(“http://xxxxxxx/?r=y”); //xxxxxx自己替换
}
add_action(‘publish_post’, ‘newPostRefresh’);
add_action(‘edit_post’, ‘newPostRefresh’);
add_action(‘delete_post’, ‘newPostRefresh’);
add_action(‘comment_post’, ‘newPostRefresh’);
add_action(‘edit_comment’, ‘newPostRefresh’);
add_action(‘delete_comment’, ‘newPostRefresh’);
add_action(‘wp_set_comment_status’, ‘newPostRefresh’);
add_action(‘switch_theme’, ‘newPostRefresh’);

 

4、自动更新Wordpress缓存:在crontab中配置每10分钟用curl访问首页更新缓存,每天凌晨对首页或者分类页面进行更新。


*/10 * * * * curl http://www.freehao123.com/?r=y 
1 1 * * * curl http://www.freehao123.com/fenye/?r=y

 

五、Wordpress Redis缓存加速效果

1、当Wordpress页面生成时,会弄成Redis缓存。

Redis-Wordpress_12

2、第二次访问该页面时,由于Redis缓存,页面执行时间降低到0.00X左右,效果明显。

Redis-Wordpress_10

3、发表评论等可以删除评论。

Redis-Wordpress_11

4、如果使用index-with-redis.php的Debug开启模式,会在页面最下方看到执行时间。

Redis-Wordpress_09

六、Wordpress Redis缓存使用小结

1、注意,Wordpress Redis缓存PHP版本在5.3以上,LNMP一键安装包在安装时需要选择PHP 5.3以上版本,而WDCP默认安装PHP是5.2.17,还需要自己手动升级PHP版本。

2、Wordpress Redis缓存加速效果无疑是明显的,特别页面多访问大的网站博客,在使用Wordpress Redis缓存加速时请禁止其它的所有缓存插件,以免造成不必要的冲突。

转至 http://www.freehao123.com/redis-wordpress/