RuntimeError:无法在分叉进程中重用连接(ruby-oci8 gem)

时间:2018-01-15 07:44:55

标签: ruby-on-rails ruby nginx unicorn

我正在

RuntimeError: The connection cannot be reused in the forked process

ruby-oci8 (2.1.3) lib/oci8/cursor.rb:28:in `__initialize'

我正在使用oracle db for rails应用程序,最近我开始使用unicornnginx部署rails应用程序,从他们开始我收到此错误请帮助。

我将ruby 1.9.3rails 3.1一起使用,这是我的unicorn.rb文件

rails_env = ENV['RAILS_ENV'] || 'production'

worker_processes 6

preload_app true

timeout 75

app_dir     = File.expand_path("../../..", __FILE__)
shared_path = "#{app_dir}/shared"
working_directory "#{app_dir}/current"

# Set up socket location
listen "#{shared_path}/sockets/unicorn.sock", :backlog => 64

# Set master PID location
pid "#{shared_path}/pids/unicorn.pid"

stderr_path "#{shared_path}/log/unicorn.log"
stdout_path "#{shared_path}/log/unicorn.log"

before_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn master intercepting TERM and sending myself QUIT instead'
    Process.kill 'QUIT', Process.pid
  end

  defined?(ActiveRecord::Base) and
    ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|
  # reset the connection since the pre-forked connection will be stale
  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
  end

  if defined?(ActiveRecord::Base)
    config = ActiveRecord::Base.configurations[Rails.env] ||
            Rails.application.config.database_configuration[Rails.env]
    config['pool'] = ENV['DB_POOL'] || 5
    ActiveRecord::Base.establish_connection(config)
  end
end

1 个答案:

答案 0 :(得分:1)

我得到了解决方案。基本上我的模型包含establish_connection这样的定义

class User < ActiveRecord::Base
  establish_connection "user_#{Rails.env}"
end

和我的unicorn.rb文件before_fork块包含以下代码。

defined?(ActiveRecord::Base) and
  ActiveRecord::Base.connection.disconnect!

我发现当你在模型中明确地写 establish_connection 时,上面的代码不起作用。要解决此问题,我必须将上述代码更改为以下代码

defined?(ActiveRecord::Base) &&
  ActiveRecord::Base.remove_connection(User) &&
  ActiveRecord::Base.connection.disconnect!

它就像一个魅力。 : - )