如何优雅地处理无法访问的数据库服务器? [英] How do I handle an unreachable database server gracefully?
问题描述
我有一个主要在 mysql 中的应用程序,但有几个页面需要连接到另一个 mssql 服务器.我已经成功地做到了这一点,但是当我在 mac 笔记本电脑上开发时,sql server 在另一台主机上,它有时不可用.当服务器不可用时,是否有一种优雅的方式来处理连接?即,我仍然希望开发和测试运行不依赖于该服务器的部分.
I have an app that is primarily in mysql, but for a few pages needs to connect to another mssql server. I have sucessfully done this, but as I develop on a mac laptop, and the sql server is on another host, it sometimes is not available. Is there a graceful way to handle the connection when the server is not available? Ie, I still want the development and tests to run the parts that do not depend on that server.
如果生产的 rails 应用程序失去与 ms sql server 的连接,这也很方便 - 能够捕获错误并显示一个很好的服务器不可用"消息可能会很好......但仍然允许不依赖于该数据库运行的应用程序的其余部分.
This could also be handy in case the production rails app loses connectivity with the ms sql server - It might be nice then to be able to catch the error and display a nice "Server unavailable" message... but still allow the rest of the app that does not depened on that database to function.
推荐答案
我会考虑在需要访问数据库的页面上使用 before 过滤器.当您检测到数据库关闭时,重定向到非数据库页面并显示错误消息.
I would look into using a before filter on the pages that need database access. When you detect that the DB is down redirect to a non database page and flash an error message.
before_filter :check_for_database
def check_for_database
begin
ActiveRecord::Base.connection_pool.with_connection {|con| con.active?}
rescue => err
flash[:error] = "The database is down, please use pages that dont require database access."
redirect_to :controller => 'home'
return
end
这灵感来自 RailsForum 上的一篇帖子这里.
This was inspired by a post on the RailsForum here.
这篇关于如何优雅地处理无法访问的数据库服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!