Chris 曾经在Gamespot工作,他在这里谈论游戏。在过去的一年党中,有无数的年轻人在不停地刷新这个网站,而此网站依然坚挺。他们每天要处理50M地页面,没有down掉。他们用Memcache做到了这点。
Memcache 是个分布式的hash,由Livejournal开发。
你会选择用Memcache吗?
Rails and Memcache
用Fragments, Actions, Sessions, Objects缓存, 你可以使用:
memcache-client
(by Robot-coop guys/Eric Hodel). Marshal.unload is 40 times faster than Object.new/loading from the database. CachedModel – integration with ActiveRecord Fragment Cache Store Memcache session store
…或者…
cache_fu插件
或者叫 acts_as_cached 2.0。它覆盖以上讨论的所有Objects,只需要配置一个YAML 文件(config/memcached.yml).提醒:不要在服务器配置文件中使用names.而是要用IPs,为了避免BIND和每次连接都连接数据库.
get_cache
expire_cache
你需要的只有这些--你过你用set_cache,你可能不清楚改插件是如何工作的。要在在after save钩子上使用缓存失效机制。例如:
class
Presentation
<
ActiveRecord
::
Base
acts_as_cached
after_save
:expire_cache
end
再如:
class Presentation < ActiveRecord :: Base
acts_as_cached :conditions => ' published = 1 '
end
Cached-scoped-finders (译者注:不知如何翻译).。这个用法将会把自定义地find方法挪到model上,然后在其中包装一些缓存机制,cache_fu插件通过AR::Base方法将这个功能有机结合起来。
class
Topic
<
ActiveRecord
::
Base
def
self.weekly_popular
Topic
.
find
:all
,
...
end
end
Topic
.
cached
(
:weekly_popular
)
用alias_method_chain方法将date加入到缓存键:
def
self.cache_key_with_date
(
id
)
...
end
class
<<
self
alias_method_chain
:cache_key
,
:date
end
用ID加载缓存:由Topic.find(1, 2, 3)转变为
Topic.get_cache(1, 2, 3),这样可以将缓存数据放入memcached,并且在以后访问他们。
user_ids
=
@topic
.
posts
.
map
(&
:user_id
).
uniq
@users
=
User
.
get_cache
(
user_ids
)
你也可以缓存关联,因此,你可以通过memcache来导航关联。
缓存重写
class
ApplicationController
<
ActionController
::
Base
before_filter
:set_cache_override
def
set_cache_override
ActsAsCached
.
skip_cache_gets
=
!!
params
[
:skip_cache
]
end
end
reset_cache:重置缓存(这段不知道改怎么翻译了:reset_cache
: Slow, uncached operations can sometimes queue up and wedge a site. Instead, issue cache resets on completion of a request, rather than expiring beforehand. That way, requests that continue to pile up will still use the cached copy until the rebuild is complete.)
class
Presentation
<
ActiveRecord
::
Base
after_save
:reset_cache
end
版本:当修改代码后地缓存方式
class
Presentation
<
ActiveRecord
::
Base
acts_as_cached
:version
=>
1
end
部署:Chris推键是一能够Monit部署以保证Memcache服务器高效率工作。(译者注:不知其他服务器效率如何)
livketama:在不使缓存实效地情况下重新部署Memcache服务器。
问题: Page caching? Nginx 会使用本地Memcache page caching,即在rails 主机之外。
后记:由于本人最近正在研究cache_fu插件地使用方法,本篇文章会持续更新,敬请关注。欢迎发表您对该插件的理解。