我正在使用 commons-dbcp2 为数据库创建一个连接池。当数据库关闭时,dataSource.getConnection()
方法需要 20 秒然后抛出异常。我想配置 DataSource
以动态更改超时,例如5 秒。
我尝试了 dataSource.setLoginTimeout()
,但 BasicDataSource
不支持它
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setInitialSize(3);
dataSource.setMaxTotal(100);
dataSource.setValidationQuery(validationquery);
dataSource.setTestOnBorrow(true);
dataSource.setRemoveAbandonedOnBorrow(true);
try (Connection connection = dataSource.getConnection()) {
} catch (Exception e) {
}
我希望在 5 秒后(按照我的配置)它抛出异常。
最佳答案
你可以试试validationQueryTimeout
parameter这让您可以在 X 秒后使验证查询超时:
dataSource.setValidationQueryTimeout(5);
dataSource.setTestOnBorrow(true);
您不必设置验证 SQL 查询,现代 JDBC 驱动程序具有 Connection.isValid()
。
不幸的是,根据 Bad Behavior: Handling Database Down,DBCP 池存在问题由于操作系统 TCP 超时限制。 2017年测试完成时:
Dbcp2 did not return a connection, and also did not timeout. The execution of the validation query is stuck due to unacknowledged TCP traffic. Subsequently, the SQL Statement run on the (bad) connection by the test harness hangs (due to unacknowledged TCP). setMaxWait(5000) is seemingly useless for handling network outages. There are no other meaningful timeout settings that apply to a network failure.
关于java - 如何使用 commons-dbcp BasicDataSource 为 getConnection 设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55496742/