需要捕获 JdbcTemplate.setQueryTimeout 的超时情况
Need to capture timeout case for JdbcTemplate.setQueryTimeout
我遇到了一个问题,当我查询 mysql 服务器时有时会挂起,有时它会完全崩溃。我正在使用 spring JdbcTemplate 连接到它。我看到 JdbcTemplate 有一个 setTimeout 方法,但我不确定如何检查是否发生超时。我这样称呼它:
try {
JdbcTemplate template = new JdbcTemplate(dataSource);
template.setQueryTimeout(3);
SqlRowSet rs = template.queryForRowSet(sql);
} catch (DataAccessException e) {
String msg = "Can't connect to database.";
response.addError(msg + " " + e);
logger.error(msg, e);
return response;
}
我知道这在数据库关闭时工作正常,但我不确定如何测试查询是否因超时而停止,或者查询是否执行正常并且没有返回记录。
添加到我的问题是我实际上无法重现服务器现在挂起的情况,所以我无法自己进行试验。我应该检查某种类型的异常,还是会抛出 DataAccessException?或者可能有一些我可以在 SqlRowSet 中检查的东西?
如果您看到 Statement.executeQuery 的文档,它确实定义了 SQLTimeoutException
。如果设置并超过了超时(有很多条件),这将被抛出 - 检查你的数据库驱动程序的文档。
Spring 的 jdbc 模板在内部调用它,java.sql 异常由 spring 的 SQLExceptionTranslator into a QueryTimeoutException
翻译
我建议捕获这个异常。
我遇到了一个问题,当我查询 mysql 服务器时有时会挂起,有时它会完全崩溃。我正在使用 spring JdbcTemplate 连接到它。我看到 JdbcTemplate 有一个 setTimeout 方法,但我不确定如何检查是否发生超时。我这样称呼它:
try {
JdbcTemplate template = new JdbcTemplate(dataSource);
template.setQueryTimeout(3);
SqlRowSet rs = template.queryForRowSet(sql);
} catch (DataAccessException e) {
String msg = "Can't connect to database.";
response.addError(msg + " " + e);
logger.error(msg, e);
return response;
}
我知道这在数据库关闭时工作正常,但我不确定如何测试查询是否因超时而停止,或者查询是否执行正常并且没有返回记录。
添加到我的问题是我实际上无法重现服务器现在挂起的情况,所以我无法自己进行试验。我应该检查某种类型的异常,还是会抛出 DataAccessException?或者可能有一些我可以在 SqlRowSet 中检查的东西?
如果您看到 Statement.executeQuery 的文档,它确实定义了 SQLTimeoutException
。如果设置并超过了超时(有很多条件),这将被抛出 - 检查你的数据库驱动程序的文档。
Spring 的 jdbc 模板在内部调用它,java.sql 异常由 spring 的 SQLExceptionTranslator into a QueryTimeoutException
翻译我建议捕获这个异常。