您的位置:首页 > 数据库 > Redis

redis实现web页面缓存

2017-06-04 18:22 169 查看

1、网页缓存

在动态生成网页的时候通常会使用模板语言来简化网页的生成操作,现在的web网页通常由头部、尾部、侧栏菜单、工具条、内容域的模板生成,有时候模板还用于生成javascript,但是对于一些不经常发生变化的页面,并不需每次访问都动态生成,对这些页面进行缓存,可以减少服务器的压力

缓存思路

在处理请求之前添加一个中间件,由这个中间件来调用redis缓存函数,对于不能缓存的页面,函数直接生成页面并返回;而能够缓存的页面,函数首先从redis缓存中去取出并返回缓存页面,如果缓存页面不存在则生成并缓存到redis数据库中5分钟

php逻辑代码

public function cache_request(){
if(!$is_cache){
//生成缓存页面并返回
return $this->template->bulde($view);
}
$page_key = 'cache:'.$view;
$content = $this->redis->get($page_key);
if(!$content){
$content = $this->template->bulde($view);
$this->redis->settx($page_key,$content,300);
}
return $content;
}


2、数据行缓存

通过网页缓存缓存已经大大的提高了网页加载的速度,而对于那些无法缓存的页面程序也可以通过数据行缓存来提高他们的加载速度

实现思路

编写一个持续运行的守护进程函数,让这个函数将指定数据行缓存到redis里面,并不定期对数据行缓存进行更新,数据行内容为json数据格式的字符。创建两个有序集合来记录何时对数据行进行更新。

一个为调度有序集合,成员为数据行ID,分值为当前时间戳

另一个为延时有序集合,成员为数据行ID,分值则记录延时多久缓存一次

将需要缓存的数据行加入到延时有序集合和调度有序集合,分值初始值为延时时间,当前时间戳。

守护进程函数从调度有序集合中取出第一行数据行ID,进行数据行缓存,缓存完毕,更新调度有序集合数据行ID的分值为当前时间戳+延时时间

php逻辑代码

调度函数:schedule_row_cache

public function schedule_row_cache($row_id , $delay){
$this->redis->zadd('delay:',$row_id,$delay);
$this->redis->zadd('schedule:'.$row_id,time());
}


守护进程函数:cache_row

public function cache_row(){
while(true){
$next = $this->redis->zrange('schedule:',0,0,withscores=TRUE);
$now = time();
if(!$next){
continue;
}
$row_id = $next[0][0];

$delay = $this->redis->zscore('delay:',$row_id);
if($delay <= 0){
$this->redis->zrem('schedule:',$row_id);
$this->redis->zrem('delay:',$row_id);
$this->redis->delete('cache_row:'.$row_id);
}
//这里Inventory的功能是获取数据行,返回的是json字符串
$row = Inventory.get($row_id);
$this->redis->zadd('schedule:',($row_id,$now+$delay));
$this->redis->set('cache_row:'.$row_id,$row);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  redis web php 缓存技术