您應該使用@Recover
註解來執行一個動作上的每個故障,並保持一個計數的對象內部的方法之外。確保沒有其他方法與此計數器交互。這是基本的前提:
@Service
class Service {
private int attemptsLeft=12;
@Retryable(maxAttempts=12, [email protected](delay=100, maxDelay=500))
public service() {
// ... do something that throws a KnownException you create to catch later on.
}
@Recover
public void connectionException(KnownException e) {
this.attemptsLeft = this.attemptsLeft-1; //decrease your failure counter
Logger.warn("Retry attempts left:{}",attemptsLeft);
}
}
如果你不想要一個成員變量跟蹤數,則可能需要溝的註釋和申報RetryTemplate
以訪問的背景下,與getRetryCount()
方法。
public String serviceWithRetry() {
RetryTemplate retryTemplate = new RetryTemplate();
final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(12);
retryTemplate.setRetryPolicy(retryPolicy);
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setInterval(100L);
retryTemplate.setBackOffPolicy(backOffPolicy);
retryTemplate.execute(new RetryCallback<Void, RuntimeException>()
return retryTemplate.execute(new RetryCallback<Void, RuntimeException>() {
@Override
public void doWithRetry(RetryContext context) {
LOG.info("Retry of connection count: {}", context.getRetryCount());
return //something with your connection logic
}
});
}
謝謝你非常喜歡這個方向。那來到我的腦海,但服務是沒有任何國家要保持一個非常併發對象。正如你在我的崗位都看到了,我也用@Async註釋,因此私人INT attemptsLeft = 12;這不可能是一種解決方法。我可以使用原子整數,但後來我還需要一種方法通過線程來區分瓦爾。其他選項將是線程本地,但我想知道爲什麼沒有更簡單的工作。或者在那裏? – Imran
謝謝,好像是沒有辦法與註解周圍。 – Imran