2013-05-29 45 views
0

我正在使用@Aspect爲數據庫過時連接問題實現重試邏輯(max_retries = 5)。在此建議中,我有一個ThreadLocal對象,用於跟蹤邏輯重試次數以獲取連接並且無論何時無法獲得連接,它都會增加,以避免過期連接問題無限次重試,最大重試次數爲5次(常量)。ThreadLocal和@Aspect註釋

但我的問題是,在這個@Aspect Java類的ThreadLocal永遠不會增加,這是造成endlees循環中的代碼,這當然應該後重試maximun數量不重試,但永遠達不到的數量和不不打破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; 
    } 
} 
+1

你能顯示代碼嗎? –

+1

你確定'e instanceof NestedRuntimeException &&((NestedRuntimeException)e).contains(staleConnectionException)'是'true?此外,我認爲在你的情況下使用ThreadLocal並不是有用的,爲什麼不在你的'retryConnection'方法中使用一個簡單的計數器? – gma

+0

是的,因爲我在日誌中看到日誌消息「遇到過時連接異常,正在重試1/5」。 – pk2

回答

1

正如在評論中提到的,不知道爲什麼你使用的線程是本地的......但是鑑於你是這樣的,可能導致無限循環的是遞歸使用這個方面。通過調試器或配置文件運行它,查看是否以嵌套方式實現同​​一方面。