6

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 を使用

4

2 に答える 2

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
于 2012-07-11T06:19:24.907 に答える
4

@Tor の応答に追加して、 に変更$redis = Redis.newRails.cache.reconnectます。

この github issue にある情報https://github.com/jodosha/redis-store/issues/21#issuecomment-948569

于 2012-08-21T18:54:35.690 に答える