Rails产生“PGError:服务器意外关闭连接”经过一段时间后 [英] Rails produces "PGError: server closed the connection unexpectedly" after some timeout

查看:261
本文介绍了Rails产生“PGError:服务器意外关闭连接”经过一段时间后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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




  • 在RHEL 5.6上运行的Rails:3.0.5

  • Postgres:8.4,在Windows Server 2008上运行
    两个服务器在同一个LAN上。



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

  ActiveRecord :: StatementInvalid(PGError:服务器意外关闭连接
这可能意味着服务器在处理请求前或处理请求时异常终止

根据我研究的内容,似乎数据库连接在Postgres超时后被删除,在这段时间内, / p>


  • 如果我向Rails发出请求(第一个请求),它将显示上面的连接错误

  • <如果我向Rails发出另一个请求(第二个请求),Rails似乎重新连接到Postgres并正常工作。


我将永远遇到第一个连接错误,然后将所有的正常操作,这是非常严重的在我的情况,因为我想提交一个无错误的响应,我的客户端。



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





任何建议,以使我的应用程序从db连接错误免费?谢谢。

解决方案

我们在Heroku上有很多问题。作为一个hackish解决方案,这里是我们做的。将以下内容放在您的ApplicationController中:

  prepend_before_filter:confirm_connection 
def confirm_connection
c = ActiveRecord :: Base.connection
begin
c.select_allSELECT 1
rescue ActiveRecord :: StatementInvalid
ActiveRecord :: Base.logger.warn重新连接到数据库
c.reconnect!
end
end

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


I have the setup of my Rails app as following:

  • Rails: 3.0.5 (under Apache proxy) running on RHEL 5.6
  • Postgres: 8.4, running on Windows Server 2008 The 2 servers are on the same LAN.

The problem is, after some idle time, when I make a new request to the Rails app, it gives me the following error:

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

From what I have researched, it seems that the database connections are dropped after some timeout by Postgres. During this time, from the Rails side,

  • if I make a request to Rails (1st request), it will display the connection error as above
  • if I make another request to Rails (2nd request), Rails seems to reconnect to Postgres and functions correctly.

It means that I will always experience the first connection error then will have all normal operation again, which is very serious in my case since I'd like to deliver a non-error response to my client.

I have looked in following questions and answers, but they do not seem to be appropriate for my case:

Do you have any advice in order to make my app free from db connection errors? Thank you.

解决方案

We had this problem on Heroku, a lot. As a hackish solution, here's what we did. Put the following in your 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

Basically, tests the connection on each controller hit. Scalable? Not really. But it fixed the problem for us.

这篇关于Rails产生“PGError:服务器意外关闭连接”经过一段时间后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆