独角兽在Heroku上与Postgres数据库的连接经常断开

4

我在Heroku上使用独角兽Web服务器设置了一个应用程序。 我的数据库设置在外部服务器(不在Heroku上)。 我已按要求配置了DATABASE_URL。 当我运行Heroku控制台时,我能够成功地在服务器上运行查询。 但是,在独角兽启动后访问URL时,我遇到了这个错误:

2014-03-14T01:44:53.820853+00:00 app[web.1]: ActiveRecord::StatementInvalid (PG::ConnectionBad: connection is closed:               SELECT a.attname, format_type(a.atttypid, a.atttypmod),
2014-03-14T01:44:53.820853+00:00 app[web.1]:                      pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
2014-03-14T01:44:53.820853+00:00 app[web.1]:                 FROM pg_attribute a LEFT JOIN pg_attrdef d
2014-03-14T01:44:53.820853+00:00 app[web.1]:                   ON a.attrelid = d.adrelid AND a.attnum = d.adnum
2014-03-14T01:44:53.820853+00:00 app[web.1]:                WHERE a.attrelid = '"currencies"'::regclass
2014-03-14T01:44:53.820853+00:00 app[web.1]:                  AND a.attnum > 0 AND NOT a.attisdropped
2014-03-14T01:44:53.820853+00:00 app[web.1]:                ORDER BY a.attnum
2014-03-14T01:44:53.820853+00:00 app[web.1]: ):
2014-03-14T01:44:53.820853+00:00 app[web.1]:   app/controllers/search_controller.rb:5:in `index'

我已按照说明进行了配置。以下是我的独角兽配置。

worker_processes Integer(ENV["WEB_CONCURRENCY"] || 2)
timeout 25
preload_app true

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

    if defined?(ActiveRecord::Base)
      ActiveRecord::Base.connection.disconnect!
      puts 'Unicorn disconnected from database'
    end

  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis.quit
    Rails.logger.info('Disconnected from Redis')
  end
end

after_fork do |server, worker|
  Signal.trap 'TERM' do
    puts 'Unicorn worker intercepting TERM and doing nothing. Wait for master to send QUIT'
  end

  if defined?(ActiveRecord::Base)
    config = Rails.application.config.database_configuration[Rails.env]
    config['reaping_frequency'] = ENV['DB_REAP_FREQ'] || 10
    config['pool'] = ENV['DB_POOL'] || 2
    ActiveRecord::Base.establish_connection(config)
    puts 'Unicorn connected to database'
  end

  # If you are using Redis but not Resque, change this
  if defined?(Resque)
    Resque.redis = $redis
    Rails.logger.info('Connected to Redis')
  end
end

为什么连接会在成功连接后关闭?(我在日志中看到独角兽已连接到数据库。)

你是如何处理这个的? - brauliobo
有没有任何网络设置会在一定时间后阻止您的连接,比如超时? - rrrrong
1个回答

0
在Rails 3 + Resque中,我必须添加这个:
Resque.after_fork do |job|
  ActiveRecord::Base.verify_active_connections! 
end

我打赌类似的方法对你也会起作用。连接池中的连接超时了,必须进行清除。不过在Rails 4中已经有了一些改变,请参见这里https://github.com/socialcast/resque-ensure-connected/issues/3


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接