我正在使用@Aspect为数据库过时的连接实现一个重试逻辑(max_retries= 5)这个建议我有一个ThreadLocal对象,它跟踪逻辑重试了多少次来获得连接,当它不能获得连接时它就会递增,所以为了避免对陈旧连接问题的无限重试,最大重试次数是5(常量)。
但我遇到的问题是,在这个@Aspect java类中,ThreadLocal永远不会递增,这会导致代码中的endlees循环,当然,在最大重试次数之后,endlees循环不应该重试,但永远不会达到那个计数,也不会中断while循环。
如果有人在@Aspect和ThreadLcal对象上遇到这个问题,请告诉我。
我很乐意分享代码。
private static ThreadLocal<Integer> retryCounter= new ThreadLocal<Integer>() {};
private static final String STALE_CONNECTION_EXCEPTION = "com.ibm.websphere.ce.cm.StaleConnectionException";
@Around("service")
public Object retryConnection(ProceedingJoinPoint pjp) throws Throwable {
if (staleConnectionException == null) {
return pjp.proceed();
}
Throwable exception = null;
retryCounter.set(new Integer(0));
while ( retryCounter.get() < MAX_TRIES) {
try {
return pjp.proceed();
}
catch (AppDataException he) {
exception = retry(he.getCause());
}
catch (NestedRuntimeException e) {
exception = retry(e);
}
}
if (exception != null) {
Logs.error("Stale connection exception occurred, no more retries left", this.getClass(), null);
logException(pjp, exception);
throw new AppDataException(exception);
}
return null;
}
private Throwable retry(Throwable e) throws Throwable {
if (e instanceof NestedRuntimeException && ((NestedRuntimeException)e).contains(staleConnectionException)) {
retryCounter.set(retryCounter.get()+1);
LogUtils.log("Stale connection exception occurred, retrying " + retryCounter.get() + " of " + MAX_TRIES, this.getClass());
return e;
}
else {
throw e;
}
}发布于 2013-05-30 04:24:07
正如评论中提到的,不确定为什么要使用线程本地...但是考虑到你是,可能导致无限循环的原因是递归地使用这个方面。通过调试器运行它或分析它,以查看您是否以嵌套的方式命中相同的方面。
发布于 2013-05-30 04:02:19
老实说,看看您的代码,我认为您最好根本不这样做,而只是在您的连接池中配置连接测试(假设您正在使用一个连接池):http://pic.dhe.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/tdat_pretestconn.html
https://stackoverflow.com/questions/16817582
复制相似问题