我有一个线程尝试使用JDBCTemplate连接到数据库,如下所示:
JDBCTemplate jdbcTemplate = new JdbcTemplate(dataSource);
try{
jdbcTemplate.execute(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws sqlException {
return con.prepareCall(query);
}
}, new CallableStatementCallback() {
@Override
public Object doInCallableStatement(CallableStatement cs)
throws sqlException {
cs.setString(1, subscriberID);
cs.execute();
return null;
}
});
} catch (DataAccessException dae) {
throw new CougarFrameworkException(
"Problem removing subscriber from events queue: "
+ subscriberID, dae);
}
我想确保如果上面的代码抛出DataAccessException或sqlException,线程会等待几秒钟并尝试重新连接,再说5次然后放弃.我怎样才能做到这一点?此外,如果在执行期间数据库关闭并再次出现,我如何确保我的程序从此恢复并继续运行而不是抛出异常并退出?
提前致谢.
解决方法:
试试这个.我的考虑是:运行一个循环,直到语句成功执行.如果发生故障,则容忍故障5次,每次等待2秒钟以进行下一次执行.
JDBCTemplate jdbcTemplate = new JdbcTemplate(dataSource);
boolean successfullyExecuted = false;
int failCount = 0;
while (!successfullyExecuted){
try{
jdbcTemplate.execute(new CallableStatementCreator() {
@Override
public CallableStatement createCallableStatement(Connection con)
throws sqlException {
return con.prepareCall(query);
}
}, new CallableStatementCallback() {
@Override
public Object doInCallableStatement(CallableStatement cs)
throws sqlException {
cs.setString(1, subscriberID);
cs.execute();
return null;
}
});
successfullyExecuted = true;
} catch (DataAccessException dae) {
if (FailedCount < 5){
FailedCount ++;
try{java.lang.Thread.sleep(2 * 1000L); // Wait for 2 seconds
}catch(java.lang.Exception e){}
}else{
throw new CougarFrameworkException(
"Problem removing subscriber from events queue: "
+ subscriberID, dae);
}
} catch (java.sql.sqlException sqle){
if (FailedCount < 5){
FailedCount ++;
}else{
try{java.lang.Thread.sleep(2 * 1000L); // Wait for 2 seconds
}catch(java.lang.Exception e){}
throw new CougarFrameworkException(
"Problem removing subscriber from events queue: "
+ subscriberID, dae);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。