5

我正在使用 postgres 9.1 org.apache.commons.dbcp.BasicDataSource(用于我的连接池)和 Java 1.7。当我重新启动我的 postgres 服务器时,我得到了像org.postgresql.util.PSQLException: FATAL: terminating connection due to administrator command.

如何使连接自动重新连接到重新启动的数据库?

4

2 回答 2

5

validationQuery根据文档, DBCP 有一个连接验证查询选项。您可以将其设置为类似的东西SELECT 1;,DBCP 将在返回连接以对其进行测试之前运行它。

也就是说,您的应用确实应该处理这种情况。SQL 查询可能由于各种原因而失败,您应该始终在具有时间回退和重试限制的重试循环中执行查询,加上一些逻辑来确定哪些异常可以在重试时恢复,哪些不能(使用 SQLState为了那个原因)。

特别是,验证受制于竞争条件,您可以在其中进行事件排序,例如:

  1. 证实
  2. 将连接传递给应用程序
  3. 服务器关闭
  4. 应用程序运行第一条语句

或者

  1. 证实
  2. 将连接传递给应用程序
  3. 应用程序运行第一个语句,打开一个事务
  4. 服务器关闭
  5. 应用程序运行第二条语句

...因此,对于您的应用来说,拥有适当的重试循环和良好的事务处理仍然很重要。

您可以从 SQLException: 中获取 SQLState SQLException.getSQLState。PostgreSQL 的代码在 PostgreSQL 手册中。

于 2013-06-04T23:45:45.557 回答
3

In this particular case the PostgreSQL connection is telling you that the server was shut down after the connection was created. DBCP connection pool does not handle this condition with it's default configuration.

Even if you set validationQuery parameter to something like SELECT 1, it will not be used, unless you also set at least one of the testOnXXXX parameters.

I usually set both testOnCreate and testOnBorrow to true.

Also check other defaults of DBCP (in the org.apache.commons.pool2.impl.BaseObjectPoolConfig), because in my opinion they are not well suited for production environments.

于 2015-04-09T09:03:55.673 回答