Caching(缓存)“缓存”什么

相关文献([url]http://www.ibm.com/developerworks/cn/web/wa-rails1/#N1007C[/url])
许多应用程序似乎都花费很多时间做重复的事情。博客应用程序提交当前文章列表给每
个访问者。商店应用程序在同一页显示产器信息给请求它的每个人。
所有重复都浪费了我们服务器的资源时间。提交博客页面可以要求半打的数据库查询,
它可以一直运行很多Ruby方法和Rails模板。它不应该对每个单独的请求都有大量的处理,
但对每小时可能一千多次的点击率,突然你的服务器会变得缓慢。你的用户看到越来越慢的
“应答”。在这些情况下,我们可以使用缓存来减少服务器上的加载操作,并提高我们应用程序的“应答”。

Rails提出了三个缓存方案。在本章,我们将讨论两种,“页缓存”和“动作缓存”。
我们在366页查看第三种,“段缓存”。

“页缓存”是最简单及最有效的Rails缓存形式。在一个用户第一次请求一个特定的URL
时,我们的应用程序得到调用并产生一个HTML页面。这个页的内容被存储在缓冲中。在下一
次收到包含那个URL的请求时,HTML页面被从缓存中直接递交。你的应用程序从没有看到请
求。事实上,Rails根本就不会弄错:请求完全在web服务器内被处理,是web服务器生成
页缓存。非常有效率。你的应用程序以服务器递交任何静态内容的同样速度递交这些页面。
有时候,我们的应用程序至少需要部分地对这些请求进行处理。例如,你的商店可能只
显示某些产品的细节给一个用户的子集(或许是高级消费者会最先访问新产品)。在这种情况
下,你显示的页将有同样的内容,但你不想显示它给任何人—你需要过滤对被缓存内容的访
问。Rails为这个目的提供了“动作缓存”。用“动作缓存”,你的应用程序“控制器”还
可以被调用并且它的before“过滤器”也会运行。只是如果有个现有的被缓存的页,则“动
作”本身不被调用。

让我们看看在一个站点内,有公共的和高级的,限于会员的内容。我们有两个“控制器”,
一个是逻辑“控制器”,它用于检验某人不是会员,一个内容“控制器”,它带有显示公共
的和高级的内容的“动作”。公共的内容由单个页面和对收费文章的连接组成。如果有请求
收费内容,而它却不是会员,我们重定向它们到注册它们的逻辑“控制器”内的一个“动作”。
忽略一会缓存,我们来实现这个应用程序的内容部分,应用程序使用了一个before“过
滤器”来校验用户的状态和用于两种内容的一组“动作”方法。

Rails的Cache分四种:
1,Page Cache - Fastest
2,Action Cache - Next Fastest
3,Fragment Cache - Least Fastest
4,ActiveRecord Cache - Only available in Edge Rails
下面一一介绍上面四种Cache以及Rails如何使用memcached

一、Page Cache
如果开发阶段要使用cache,则需要先设置好config/environments/development.rb:
config.action_controller.perform_caching = true
而production环境下默认是开启cache功能的
Page Cache是Rails中最快的cache机制,使用Page Cache的前提一般为:
1,需要cache的page对所有用户一致
2,需要cache的page对public可访问,不需要authentication
Page Cache使用起来很简单:

class BlogController < ApplicationController
caches_page :list, :show
def list
Post.find(:all, \:order => "created_on desc", :limit => 10)
end

def show
@post = Post.find(params[:id])
end
end

这样我们就对BlogController的list和show页面进行了缓存
这样做的效果是第一次访问list和show页面时生成了public/blog/list.html和public/blog/show/5.html这两个html页面

对于分页情况下的cache,我们需要把url的page参数改写成"blog/list/:page"这种形式,而不是"blog/list?page=1"这种形式
这样cache的html页面即为public/blog/list/1.html
当数据更改时我们需要清除旧的缓存,我们采用Sweepers来做是非常不错的选择,这把在BlogController里清除缓存的代码分离出来

首先编辑config/environment.rb:
Rails::Initializer.run do |config|
# ...
config.load_paths += %w(#{RAILS_ROOT}/app/sweepers)
# ...

这告诉Rails加载#{RAILS_ROOT}/app/sweepers目录下的文件
我们为BlogController定义app/sweepers/blog_sweeper.rb:
class BlogSweeper < ActionController::Caching::Sweeper
observe Post # This sweeper is going to keep an eye on the Post model

# If our sweeper detects that a Post was created call this
def after_create(post)
expire_cache_for(post)
end

# If our sweeper detects that a Post was updated call this
def after_update(post)
expire_cache_for(post)
end

# If our sweeper detects that a Post was deletedcall this
def after_destroy(post)
expire_cache_for(post)
end

private
def expire_cache_for(record)
# Expire the list page now that we posted a new blog entry
expire_page(:controller => 'blog', :action => 'list')

# Also expire the show page, in case we just edit a blog entry
expire_page(:controller => 'blog', :action => 'show', :id => record.id)
end
end

然后我们在BlogController里加上该sweeper即可:

class BlogController < ApplicationController
caches_page :list, :show
cache_sweeper :blog_sweeper, \:only => [:create, :update, :destroy]
# ...
end

我们可以配置cache的静态html文件的存放位置,这在config/environment.rb里设置:

config.action_controller.page_cache_directory = RAILS_ROOT + "/public/cache/"

然后我们设置Apache/Lighttpd对于静态html文件render时不接触Rails server即可
所以Page Cache就是最快的Cache,因为它不与Rails server打交道,直接load静态html

二、Action Cache
Action Cache相关的helper方法是caches_action和expire_action,其他基本和Page Cache一样
另外我们还可以运行rake tmp:cache:clear来清空所有的Action Cache和Fragment Cache

class BlogController < ApplicationController
before_filter :authentication
caches_action :list, :show
cache_sweeper :blog_sweeper, \:only => [:create, :update, :destroy]

如上代码所示,我们将authentication这个filter放在caches_action之前声明,这样我们的Action Cache在执行之前会先访问authentication方法
这样可以弥补Page Cache不能对需要登录认证的Page进行Cache的缺点
生成的cache文件为tmp/cache/localhost:3000/blog/list.cache,这样对不同subdomain的访问页面可以cache到不同的目录
由于每次访问Action Cache时都需要与Rails server打交道,并且要先运行filters,所以比Page Cache的效率稍低

三、Fragment Cache
Fragment Cache用于处理rhtml页面中的部分需要cache的模块,如app/views/blog/list.rhtml:


<strong>My Blog Posts</strong>
<% cache do %>
<ul>
<% for post in @posts %>
<li><%= link_to post.title, :controller => 'blog', :action => 'show', :id => post %></li>
<% end %>
</ul>
<% end %>

生成的cache文件为/tmp/cache/localhost:3000/blog/list.cache
我们需要在BlogController的list方法里加上一行判断,如果是读取Fragment Cache,则不必再查询一次数据库:

def list
unless read_fragment({})
@post = Post.find(:all, \:order => 'created_on desc', :limit => 10)
end
end

Fragment分页时的Cache:


def list
unless read_fragment({:page => params[:page] || 1}) # Add the page param to the cache naming
@post_pages, @post = paginate :posts, :per_page => 10
end
end

rhtml页面也需要改写:


<% cache ({:page => params[:page] || 1}) do %>
... All of the html to display the posts ...
<% end %>

生成的cahce文件为/tmp/cache/localhost:3000/blog/list.page=1.cache
从分页的Fragment Cache可以看出,Fragment Cache可以添加类似名字空间的东西,用于区分同一rhtml页面的不同Fragment Cache,如:


cache ("turkey") => "/tmp/cache/turkey.cache"
cache (:controller => 'blog', :action => 'show', :id => 1) => "/tmp/cache/localhost:3000/blog/show/1.cache"
cache ("blog/recent_posts") => "/tmp/cache/blog/recent_posts.cache"
cache ("#{request.host_with_port}/blog/recent_posts") => "/tmp/cache/localhost:3000/blog/recent_posts.cache"

清除Fragment Cache的例子:
expire_fragment(:controller => 'blog', :action => 'list', :page => 1)
expire_fragment(%r{blog/list.*})


四、ActiveRecord Cache
Rails Edge中ActiveRecord已经默认使用SQl Query Cache,对于同一action里面同一sql语句的数据库操作会使用cache

五、memcached
越来越多的大型站点使用memcached做缓存来加快访问速度
memcached是一个轻量的服务器进程,通过分配指定数量的内存来作为对象快速访问的cache
memcached就是一个巨大的Hash表,我们可以存取和删除key和value:

@tags = Tag.find :all
Cache.put 'all_your_tags', @tags
Cache.put 'favorite_skateboarder', 'Tom Penny'
skateboarder = Cache.get 'favorite_skateboarder'
Cache.delete 'all_your_tags'

我们可以使用memcached做如下事情:
1,自动缓存数据库的一行作为一个ActiveRecord对象
2,缓存render_to_string的结果
3,手动存储复杂的数据库查询作为缓存
cached_model让我们轻松的缓存ActiveRecord对象,memcahed-client包含在cached_model的安装里,memcahed-client提供了缓存的delete方法
Java代码
sudo gem install cached_model

我们在config/environment.rb里添加如下代码来使用memcached:
require 'cached_model'

memcache_options = {
:c_threshold => 10_000,
:compression => true,
:debug => false,
:namespace => 'my_rails_app',
:readonly => false,
:urlencode => false
}

CACHE = MemCache.new memcache_options
CACHE.servers = 'localhost:11211'

对于production环境我们把上面的代码挪到config/environments/production.rb里即可
然后让我们的domain model集成CachedModel而不是ActiveRecord::Base
class Foo < CachedModel
end

然后我们就可以使用memcached了:
all_foo = Foo.find :all
Cache.put 'Foo:all', all_foo
Cache.get 'Foo:all'

需要注意的几点:
1,如果你查询的item不在缓存里,Cache.get将返回nil,可以利用这点来判断是否需要重新获取数据并重新插入到缓存
2,CachedModel的记录默认15分钟后expire,可以通过设置CachedModel.ttl来修改expiration time
3,手动插入的对象也会过期,Cache.put('foo', 'bar', 60)将在60秒后过期
4,如果分配的内存用尽,则older items将被删除
5,可以对每个app server启动一个memcached实例,分配128MB的内存对一般的程序来说足够
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值