WordPress给网站配置Redis 缓存的例子

我下面提出的解决方案是在 Redis 中缓存所有输出的 HTML 内容而无需再让 WordPress 重复执行页面脚本。这里使用 Redis 代替 Varnish 设置简单,而且可能更快。

安装 Redis

如果你使用的是 Debian 或者衍生的操作系统可使用如下命令安装 Redis:

 apt-get install redis-server

使用 Predis 作为 Redis 的 PHP 客户端
你需要一个客户端开发包以便 PHP 可以连接到 Redis 服务上。

这里我们推荐 Predis. 上传 predis.php 到 WordPress 的根目录。

前端缓存的 PHP 脚本

步骤1: 在 WordPress 的根目录创建新文件 index-with-redis.php ,内容如下:

 

 代码如下 复制代码

 <?php
// 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 PredisClient('');

// 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(yun_qi_img/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.aips.me/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);
}

?>

你也可以在 Github 上查看 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 秒
我已经在我的博客中使用了如上的方法进行加速很长时间了,一切运行良好。

其他建议
本文作者的 WordPress 环境是 Nginx + PHP-FPM + APC + Cloudflare + Redis. 安装在一个 VPS 中,无缓存插件。

请确认使用了 gzip 压缩,可加快访问速度。

访问 wp-admin
要访问 wp-admin 必须使用 /wp-admin/index.php 代替原来的 /wp-admin/.

本文其实在国内已经有很翻译过了,但我看到作者也一直在更新此文,反而国内译者都不怎么更新,我就自己去重新折腾了一遍。

时间: 2024-12-21 16:16:59

WordPress给网站配置Redis 缓存的例子的相关文章

spring boot 配置redis缓存

问题描述 spring boot 配置redis缓存 环境:spring boot+java8,spring版本为4以上 用spring boot 配置redis缓存时报错如下: java.lang.IllegalStateException: No CacheResolver specified, and no unique bean of type CacheManager found. Mark one as primary (or give it the name 'cacheManag

利用Redis缓存提高斐波拉契数列程序的性能例子

去某家公司面试,PHP岗位,先做笔试,再两轮面试,最后hr面,拿了offer.   笔试题都不难,做完随手拍了一张,然后回去把这道求斐波那契数列的题在电脑上运行了一遍,写的当然是对的,但是当你要求第N位,当N大于60的时候就会非常慢了,后来就想着用Redis缓存来优化性能,效果非常惊人!     我把题目改了一下,也是要用递归,但是是要列出从0到n的斐波那契数列,并且用Redis缓存.   思路很简单,每次取第n的值的时候判断Redis有没有,有就不用再去计算了,没有就计算一次存下来,大大减少计

WordPress优化利用Nginx fastcgi_cache缓存加速

高并发网站架构的核心原则其实就一句话"把所有的用户访问请求都尽量往前推",即:能缓存在用户电脑本地的,就不要让他去访问CDN. 能缓存CDN服务器上的,就不要让CDN去访问源(静态服务器)了.能访问静态服务器的,就不要去访问动态服务器.以此类推:能不访问数据库和存储就一定不要去访问数据库和存储. WordPress最好的优化方式就是尽量不安装插件,之前有分享过<wordpress启动Redis缓存加速>,Wordpress是典型的PHP-MySQL应用,去做数据库缓存,倒不

Redis缓存之Set使用及redis遇到的一些问题

Redis缓存Set使用 在Redis中,我们可以将Set类型看作为没有排序的字符集合,和List类型一样,我们也可以在该类型的数据值上执行添加.删除或判断某一元素是否存在等操作.需要说明的是,这些操作的时间复杂度为O(1),即常量时间内完成次操作.Set可包含的最大元素数量是4294967295. 和List类型不同的是,Set集合中不允许出现重复的元素,这一点和C++标准库中的set容器是完全相同的.换句话说,如果多次添加相同元素,Set中将仅保留该元素的一份拷贝.和List类型相比,Set

如何用Redis缓存改善数据库查询性能?

调整一个关系型数据库以实现高性能查询是一个困难的工作.如果优化数据模型和调整查询方式都不起作用,那么管理员可以使用一个诸如Redis这样的缓存技术,这是一个提供内存内和持久数据存储的关键值数据存储方法. 因为Redis具有在数据存储中快速读写数据的能力,所以它比关系型数据库更具有性能优势.但是,关键值数据存储是简单的;它们没有一个类似于SQL的查询语言或者结构化的数据模型.相反,它们有一个把键值作为与数值相关的标识符来使用的简单字典或哈希模式.管理员使用这些键来进行数值的存储和检索. 键值存储是

spring-boot | 整合Redis缓存数据

spring boot 整合redis非常简单,首先创建spring boot的Maven项目,然后在pom.xml文件中引入redis的依赖. 引入redis的依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 添加redis的

Redis 缓存 + Spring 的集成示例

SpringSession和Redis实现Session跨域 http://www.ithao123.cn/content-11111681.html   tomcat中创建session很耗服务器内存 原生session与session in redis对比下面是从stackoverflow上找到的一些观点: Using something like Redis for storing sessions is a great way to get more performance out of

详解Centos7下配置Redis并开机自启动_Redis

本篇文章主要介绍了Centos7下配置Redis并开机自启动,具有一定的参考价值,感兴趣的小伙伴们可以参考一下. 最近在做作业的时候需要用到Redis缓存,由于每次重启服务器都需要重新启动Redis,也是忒烦人,于是就有了这一篇博客,好,废话不多说. 只有两个步骤: 1.设置redis.conf中daemonize为yes,确保守护进程开启. 2.编写开机自启动脚本 基本原理为:  系统开机启动时会去加载/etc/init.d/下面的脚本,通常而言每个脚本文件会自定义实现程序的启动:若想将新的程

Redis 缓存 + Spring 的集成示例(转)

<整合 spring 4(包括mvc.context.orm) + mybatis 3 示例>一文简要介绍了最新版本的 Spring MVC.IOC.MyBatis ORM 三者的整合以及声明式事务处理.现在我们需要把缓存也整合进来,缓存我们选用的是 Redis,本文将在该文示例基础上介绍 Redis 缓存 + Spring 的集成.关于 Redis 服务器的搭建请参考博客<Redhat5.8 环境下编译安装 Redis 并将其注册为系统服务>. 1. 依赖包安装 pom.xml