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'
いくつか読んだところ、各 Passenger ワーカー インスタンスは独自の 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
コード全体で $redis を介して Redis アクセスが行われると仮定すると、このソリューションは優れています。
Rails.cache
私の質問は、読み取り、書き込みなどの操作を行うときに使用される新しい Redis 接続を作成するにはどうすればよいですか?
私のconfig/environments/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 を使用