0

我正在使用@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;
    }
}
4

2 回答 2

1

正如评论中提到的,不知道你为什么使用本地线程......但鉴于你是,可能导致无限循环的原因是递归使用这方面。通过调试器运行它或对其进行分析,以查看您是否以嵌套方式触及相同的方面。

于 2013-05-29T20:24:07.457 回答
0

老实说,看看你的代码,我认为你最好不要这样做,而只是在你的连接池中配置连接测试(假设你正在使用一个): http: //pic.dhe.ibm。 com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.nd.multiplatform.doc/info/ae/ae/tdat_pretestconn.html

于 2013-05-29T20:02:18.803 回答