Restarting the Rails Redis Cache Store to connect to the passenger fork

I want to use redis cache store (using redis-store gem).

It works fine locally, but as production continues, when Passenger launches several instances of Rails workers, we get Redis errors that indicate synchronization problems between different instances related to Redis access.

An example of such an error is

 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'

I read and realized that each instance of a working passenger must create their own Redis connection. This can be implemented using the following code

#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

Assuming Redis is accessed through $ redis throughout the code, this solution is excellent.

: Redis, , Rails.cache, , ..??

my config/environment/production.rb :

config.cache_store = :redis_store, { :host => 'localhost', :port => 6379, :thread_safe => true } 

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

+5
2

redis: https://github.com/jodosha/redis-store/blob/master/redis-activesupport/lib/active_support/cache/redis_store.rb

, :

if defined?(PhusionPassenger)
  PhusionPassenger.on_event(:starting_worker_process) do |forked|
    if forked
      Rails.cache.reconnect
    end
  end
end
+6

@Tor, $redis = Redis.new Rails.cache.reconnect.

, github, https://github.com/jodosha/redis-store/issues/21#issuecomment-948569

+4