当前位置:编程学习 > 网站相关 >>

ActiveRecord对象缓存配置

second_level_cache的使用
 
在Gemfile里面添加:
 
gem "second_level_cache", :git => "git://github.com/csdn-dev/second_level_cache.git"
使用非常简单:
 
class User < ActiveRecord::Base
  acts_as_cached
end
完整设置:
 
class User < ActiveRecord::Base
  acts_as_cached(:version => 1, :expires_in => 1.week)
end
对象缓存的key结构示例:cache_prefix/model/id/version
 
version参数非常有用,当你使用migration修改Model的schema,升级生产环境代码之后,由于Model的Cache还是老的schema,可能会导致应用程序出错,除非你清理所有的Model Cache。所以当你的Model schema修改之后,你可以相应修改版本号,这样会修改Cache的key,避免程序出错问题。Model的默认版本号是0。
 
对Model使用对象缓存之后,单对象读取,以及关联对象读取将自动访问和填充缓存,不需要编码。个别情况下你可能需要对缓存进行过期操作:
 
user = User.find(id)
user.expire_second_level_cache
 
user.write_second_level_cache
或者
 
User.expire_second_level_cache(id)
更多使用方法请参考:Second level cache
 
second_level_cache的配置
 
对象缓存的配置有3项,如果在Rails里面使用,参考Rails缓存配置,如果不在Rails里面使用,需要自己配置。
 
使用memcached
在Gemfile里面添加如下gem:
 
gem 'dalli'
gem 'kgio'
在配置文件application.rb或者相应配置文件当中配置如下:
 
require 'dalli'
require 'active_support/cache/dalli_store'
Dalli.logger = logger
CACHE = ActiveSupport::Cache::DalliStore.new("127.0.0.1")
如果是分布式memcached,配置如下:
 
CACHE = ActiveSupport::Cache::DalliStore.new("127.0.0.1", "127.0.0.2")
然后初始化second_level_cache:
 
SecondLevelCache.configure do |config|
  config.cache_store = CACHE
  config.logger = logger
  config.cache_key_prefix = 'domain'
end
使用redis
在Gemfile里面添加如下gem:
 
gem 'redis'
gem 'hiredis'
gem 'redis-activesupport'
在配置文件application.rb或者相应配置文件当中配置如下:
 
require 'redis-activesupport'  www.zzzyk.com
CACHE = ActiveSupport::Cache::RedisStore.new :host => "127.0.0.1", :driver => :hiredis
如果是分布式redis,配置如下:
 
CACHE = ActiveSupport::Cache::RedisStore.new [{:host => "127.0.0.1", :port => 6379, :driver => :hiredis}, {:host => "127.0.0.1", :port => 6380, :driver => :hiredis}]
然后初始化second_level_cache:
 
SecondLevelCache.configure do |config|
  config.cache_store = CACHE
  config.logger = logger
  config.cache_key_prefix = 'domain'
end
补充:综合编程 , 其他综合 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,