在初始化程序中设置cache_store

Jac*_*Chu 19 ruby caching ruby-on-rails redis ruby-on-rails-3

我正在尝试使用redis-store作为我的Rails 3 cache_store.我还有一个初始化器/ app_config.rb,它为配置设置加载一个yaml文件.在我的初始化程序/ redis.rb中,我有:

MyApp::Application.config.cache_store = :redis_store, APP_CONFIG['redis'] 
Run Code Online (Sandbox Code Playgroud)

但是,这似乎不起作用.如果我做:

Rails.cache
Run Code Online (Sandbox Code Playgroud)

在我的rails控制台中,我可以清楚地看到它正在使用

ActiveSupport.Cache.FileStore
Run Code Online (Sandbox Code Playgroud)

作为缓存存储而不是redis-store.但是,如果我在application.rb文件中添加配置,如下所示:

config.cache_store = :redis_store 
Run Code Online (Sandbox Code Playgroud)

它运行得很好,除了在app.rb之后加载app config初始化程序,所以我没有访问APP_CONFIG.

有没有人经历过这个?我似乎无法在初始化程序中设置缓存存储.

Jac*_*Chu 21

经过一些 研究,可能的解释是initialize_cache初始化程序在rails/initializers之前运行.因此,如果之前未在执行链中定义,则不会设置缓存存储.您必须在链中更早地配置它,例如在application.rb或environments/production.rb中

我的解决方案是在app配置之前移动APP_CONFIG加载:

APP_CONFIG = YAML.load_file(File.expand_path('../config.yml', __FILE__))[Rails.env]
Run Code Online (Sandbox Code Playgroud)

然后在同一个文件中:

config.cache_store = :redis_store, APP_CONFIG['redis']
Run Code Online (Sandbox Code Playgroud)

另一个选择是将cache_store放在before_configuration块中,如下所示:

config.before_configuration do
  APP_CONFIG = YAML.load_file(File.expand_path('../config.yml', __FILE__))[Rails.env]
  config.cache_store = :redis_store, APP_CONFIG['redis']
end
Run Code Online (Sandbox Code Playgroud)


fie*_*edl 6

它们在 初始化config/initializers之后运行Rails.cache,但在config/application.rb和之后运行config/environments

config/application.rb 或环境中的配置

config/application.rb因此,一种解决方案是在或中配置缓存config/environments/*.rb

配置在 config/initializers/cache.rb 中

如果有意在初始化程序中配置缓存,可以通过Rails.cache在配置后手动设置来完成:

# config/initializers/cache.rb
Rails.application.config.cache_store = :redis_store, APP_CONFIG['redis']

# Make sure to add this line (http://stackoverflow.com/a/38619281/2066546):
Rails.cache = ActiveSupport::Cache.lookup_store(Rails.application.config.cache_store)
Run Code Online (Sandbox Code Playgroud)

添加规格

为了确保它有效,请添加如下规范:

# spec/features/smoke_spec.rb
require 'spec_helper'

feature "Smoke test" do
  scenario "Testing the rails cache" do
    Rails.cache.write "foo", "bar"
    expect(Rails.cache.read("foo")).to eq "bar"
    expect(Rails.cache).to be_kind_of ActiveSupport::Cache::RedisStore
  end
end
Run Code Online (Sandbox Code Playgroud)

更多信息