LoginSignup
3
3

More than 5 years have passed since last update.

spork + redis-rb でのエラー対処: "Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking."

Last updated at Posted at 2012-10-10

問題

redis-rb gemsを2.2から3.0.1にアップデートしたとき,sporktを使ってspecを走らせると以下のようなエラーが出た.

Tried to use a connection from a child process without reconnecting. You need to reconnect to Redis after forking.

原因

redis-rb 3以降では,forkしたときに親と子でredisのコネクションを共有していると例外を投げるようになったらしい.
ref: https://github.com/redis/redis-rb/blob/master/lib/redis/client.rb#L277

対処

sporkがforkしたときに再度コネクションを確立するようにSpork.each_run内に以下のようなコードを書く.

spec_helper.rb
Spork.each_run do
  # This code will be run each time you run your specs.
  load Rails.root.join('config/initializers/redis.rb')
end
config/initializers/redis.rb
$redis = Redis.new(:host => 'localhost', :port => 6379)
$redis.ping

$redis.pingしてるのはRedis接続をチェックしてからRailsサーバー起動にあるハック

Unicornでも同じように,

  • before_forkで$redis.quit
  • after_forkでRedisコネクションを作成

という処理が必要.

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3