我使用tornado(4.2.1)+ momoko(2.2.0)+ psycopg2(2.6.1)进行小型Web应用程序,直到PostgreSQL服务器关闭连接才能正常工作。然后在每个db.execute()命令后,我收到一条错误消息:
@Html.DropDownListFor(x => x.ProjectID, Model.Projects, string.Empty)
这是一段代码:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\web.py", line 1415, in _execute
result = yield result
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 870, in run
value = future.result()
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 876, in run
yielded = self.gen.throw(*exc_info)
File "server.py", line 63, in get
cursor = yield self.db.execute(query)
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\gen.py", line 870, in run
value = future.result()
File "C:\Python27\lib\site-packages\tornado-4.2.1-py2.7-win32.egg\tornado\concurrent.py", line 215, in result
raise_exc_info(self._exc_info)
File "D:\work\program-stat\momoko\connection.py", line 453, in when_available
future_or_result = method(conn, *args, **kwargs)
File "D:\work\program-stat\momoko\connection.py", line 743, in execute
cursor.execute(operation, parameters)
File "C:\Python27\lib\site-packages\psycopg2\extras.py", line 288, in execute
return super(NamedTupleCursor, self).execute(query, vars)
OperationalError: server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
如何在不重新启动应用程序的情况下自动处理此异常并重新连接到数据库?
答案 0 :(得分:0)
你可以添加参数:
raise_connect_errors=False,
创建连接池时:
self.db = momoko.Pool(
dsn='dbname=%s user=%s password=%s '
'host=%s port=5432' % (
tornado.options.options.pgsql_database,
tornado.options.options.pgsql_user,
tornado.options.options.pgsql_password,
tornado.options.options.pgsql_host),
cursor_factory=NamedTupleCursor,
raise_connect_errors=False,
)
但它并不总是有用。
答案 1 :(得分:0)
如果与数据库Postgres的连接被破坏 - momoko无法重新创建连接池。 要解决此问题,您需要重新启动应用程序。为了使这个过程自动化,我编写了一个使用内置龙卷风更新机制的小脚本。
每1秒测试一次数据库连接是否存活。 在启动ioloop之前添加此检查。
导入重新加载 check_connect = tornado.ioloop.PeriodicCallback(lambda:reload.reload_if_db_pool_is_dead(application.db),1000) check_connect.start()
https://gist.github.com/MaxRV/d7180e63d6b5396d904d446653aa7e88