gpt4 book ai didi

java - 如何使用 JDBCTemplate 使线程尝试重新连接到数据库 x 次

转载 作者:搜寻专家 更新时间:2023-11-01 03:14:26 25 4
gpt4 key购买 nike

我有一个线程尝试使用 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);
}
}
}

关于java - 如何使用 JDBCTemplate 使线程尝试重新连接到数据库 x 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2866594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com