ruby-on-rails - Rails 在超时后产生 "PGError: server closed the connection unexpectedly"

标签 ruby-on-rails windows postgresql timeout connection

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

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

问题是,在闲置一段时间后,当我向 Rails 应用程序发出新请求时,出现以下错误:

ActiveRecord::StatementInvalid (PGError: server closed the connection unexpectedly
    This probably means the server terminated abnormally
    before or while processing the request.

根据我的研究,数据库连接似乎在 Postgres 超时后断开。在此期间,从 Rails 方面,

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

这意味着我总是会遇到第一个连接错误,然后会再次进行所有正常操作,这对我来说非常严重,因为我想向我的客户提供无错误响应。

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

为了使我的应用程序免受数据库连接错误的影响,您有什么建议吗?谢谢。

最佳答案

我们在 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

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

关于ruby-on-rails - Rails 在超时后产生 "PGError: server closed the connection unexpectedly",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8060024/

相关文章:

ruby-on-rails - 为下一个 API 版本使用不同的 gem 的版本控制

c++ - 发现在我的 C++ 应用程序中创建线程的原因及其作用的最佳方法是什么?

c# - 无法首先使用 Postgresql 和 Entity Framework 代码在 PostgreSQL 中创建数据库

ruby-on-rails - rails 3 : respond_with errors on undefined URL helper

ruby-on-rails - 在 rails 中查看演示者

ruby-on-rails - 单点登录,使用 ruby​​ on rails 中的逻辑分析进行授权

postgresql - Postgres 在数据库 : Could not detect default username 上运行查询时出错

mysql - SQL从两个表更新余额

ruby-on-rails - ruby rails : Validate HTML and CSS on file upload

c - Windows 内核驱动程序 : ZwAllocateVirtualMemory causing thread to terminate