一些超时后,Rails产生"PGError:服务器意外关闭了连接"

Anh*_*yen 6 windows postgresql connection timeout ruby-on-rails

我有我的Rails应用程序的设置如下:

  • Rails:在RHEL 5.6上运行的3.0.5(在Apache代理下)
  • Postgres:8.4,在Windows Server 2008上运行这两台服务器位于同一个LAN上.

问题是,在一些空闲时间之后,当我向Rails应用程序发出新请求时,它会给我以下错误:

ActiveRecord::StatementInvalid (PGError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.
Run Code Online (Sandbox Code Playgroud)

根据我的研究,似乎在Postgres超时后数据库连接被删除.在此期间,从Rails方面,

  • 如果我向Rails(第一个请求)发出请求,它将显示如上所述的连接错误
  • 如果我向Rails发出另一个请求(第二个请求),Rails似乎重新连接到Postgres并正常运行.

这意味着我将始终遇到第一个连接错误然后将再次进行所有正常操作,这在我的情况下是非常严重的,因为我想向我的客户端提供非错误响应.

我查看了以下问题和答案,但它们似乎不适合我的情况:

你有任何建议,以使我的应用程序免受数据库连接错误?谢谢.

Iro*_*com 5

我们在 Heroku 上经常遇到这个问题。作为一个骇人听闻的解决方案,这就是我们所做的。将以下内容放入您的 ApplicationController 中:

prepend_before_filter :confirm_connection
def confirm_connection
  c = ActiveRecord::Base.connection
  begin
    c.select_all "SELECT 1"
  rescue ActiveRecord::StatementInvalid
    ActiveRecord::Base.logger.warn "Reconnecting to database"
    c.reconnect!
  end
end
Run Code Online (Sandbox Code Playgroud)

基本上,测试每个控制器命中的连接。可扩展?并不真地。但它为我们解决了问题。


Woa*_*dae 1

在database.yml中,您是否reconnect: true为连接设置了选项?前任:

production:
  adapter:   postgresql
  database:  myapp
  username:  deploy
  password:  password
  reconnect: true
Run Code Online (Sandbox Code Playgroud)

我不确定具体的错误,但如果没有此选项,您需要自己处理一类预期的数据库错误。