我正在使用@Aspect 为数据库过时的连接问题实现重试逻辑(max_retries = 5)。在这个建议中,我有一个 ThreadLocal 对象,它跟踪逻辑重试获取连接的次数,并且在它无法获取时递增连接,因此为避免因过时连接问题无限重试,最大重试次数为 5(恒定)。
但我遇到的问题是,在这个@Aspect java 类中,ThreadLocal 永远不会增加,这会导致代码中出现 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;
}
}