在Passenger fork上重新启动Rails Redis缓存存储连接

Ere*_*bih 5 caching ruby-on-rails passenger redis

我想使用redis缓存存储(使用redis-store gem).

它在本地工作正常,但是当进行生产时Passenger分叉Rails工作者的多个实例时,我们得到Redis错误,这表明有关Redis访问的不同实例之间存在同步问题.

这种错误的一个例子是

 Got '7' as initial reply byte. If you're running in a multi-threaded environment, make sure you pass the :thread_safe option when initializing the connection. If you're in a forking environment, such as Unicorn, you need to connect to Redis after forking.
  redis (2.2.2) lib/redis/connection/ruby.rb:78:in `format_reply'
Run Code Online (Sandbox Code Playgroud)

我做了一些阅读并了解到每个Passenger worker实例必须创建自己的Redis连接.这可以使用以下代码实现

#config/initializers/redis_fork_init.rb
if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
      $redis = Redis.new
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

假设Redis访问是通过遍布代码的$ redis完成的 - 这个解决方案很棒.

我的问题是 - 如何创建一个新的Redis连接,当我进行Rails.cache读,写等操作时将会使用它?

我的config/environments/production.rb包括以下内容:

config.cache_store = :redis_store, { :host => 'localhost', :port => 6379, :thread_safe => true } 
Run Code Online (Sandbox Code Playgroud)

使用Rails 3.2.3,Redis 2.2.2,redis-store 1.1.1,Passenger 3.0

Tor*_*Tor 6

看看redis商店的重新连接方法:https: //github.com/jodosha/redis-store/blob/master/redis-activesupport/lib/active_support/cache/redis_store.rb

所以基本上你的fork块应该是这样的:

if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
      Rails.cache.reconnect
    end
  end
end
Run Code Online (Sandbox Code Playgroud)