use of cn.taketoday.retry.RetryContext in project today-infrastructure by TAKETODAY.
the class StatefulRetryIntegrationTests method testExponentialBackOffIsExponential.
@Test
public void testExponentialBackOffIsExponential() throws Throwable {
ExponentialBackOffPolicy policy = new ExponentialBackOffPolicy();
policy.setInitialInterval(100);
policy.setMultiplier(1.5);
RetryTemplate template = new RetryTemplate();
template.setBackOffPolicy(policy);
final List<Long> times = new ArrayList<Long>();
RetryState retryState = new DefaultRetryState("bar");
for (int i = 0; i < 3; i++) {
try {
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
times.add(System.currentTimeMillis());
throw new Exception("Fail");
}
}, new RecoveryCallback<String>() {
public String recover(RetryContext context) throws Exception {
return null;
}
}, retryState);
} catch (Exception e) {
assertTrue(e.getMessage().equals("Fail"));
}
}
assertEquals(3, times.size());
assertTrue(times.get(1) - times.get(0) >= 100);
assertTrue(times.get(2) - times.get(1) >= 150);
}
use of cn.taketoday.retry.RetryContext in project today-infrastructure by TAKETODAY.
the class RetryTemplate method doExecute.
/**
* Execute the callback once if the policy dictates that we can, otherwise execute the
* recovery callback.
*
* @param recoveryCallback the {@link RecoveryCallback}
* @param retryCallback the {@link RetryCallback}
* @param state the {@link RetryState}
* @param <T> the type of the return value
* @param <E> the exception type to throw
* @return T the retried value
* @throws ExhaustedRetryException if the retry has been exhausted.
* @throws E an exception if the retry operation fails
* @see RetryOperations#execute(RetryCallback, RecoveryCallback, RetryState)
*/
protected <T, E extends Throwable> T doExecute(RetryCallback<T, E> retryCallback, RecoveryCallback<T> recoveryCallback, RetryState state) throws E, ExhaustedRetryException {
RetryPolicy retryPolicy = this.retryPolicy;
BackOffPolicy backOffPolicy = this.backOffPolicy;
// Allow the retry policy to initialise itself...
RetryContext context = open(retryPolicy, state);
if (logger.isTraceEnabled()) {
logger.trace("RetryContext retrieved: {}", context);
}
// Make sure the context is available globally for clients who need
// it...
RetrySynchronizationManager.register(context);
Throwable lastException = null;
boolean exhausted = false;
try {
// Give clients a chance to enhance the context...
boolean running = doOpenInterceptors(retryCallback, context);
if (!running) {
throw new TerminatedRetryException("Retry terminated abnormally by interceptor before first attempt");
}
// Get or Start the backoff context...
BackOffContext backOffContext = null;
Object resource = context.getAttribute("backOffContext");
if (resource instanceof BackOffContext) {
backOffContext = (BackOffContext) resource;
}
if (backOffContext == null) {
backOffContext = backOffPolicy.start(context);
if (backOffContext != null) {
context.setAttribute("backOffContext", backOffContext);
}
}
/*
* We allow the whole loop to be skipped if the policy or context already
* forbid the first try. This is used in the case of external retry to allow a
* recovery in handleRetryExhausted without the callback processing (which
* would throw an exception).
*/
while (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
try {
if (logger.isDebugEnabled()) {
logger.debug("Retry: count={}", context.getRetryCount());
}
// Reset the last exception, so if we are successful
// the close interceptors will not think we failed...
lastException = null;
return retryCallback.doWithRetry(context);
} catch (Throwable e) {
lastException = e;
try {
registerThrowable(retryPolicy, state, context, e);
} catch (Exception ex) {
throw new TerminatedRetryException("Could not register throwable", ex);
} finally {
doOnErrorInterceptors(retryCallback, context, e);
}
if (canRetry(retryPolicy, context) && !context.isExhaustedOnly()) {
try {
backOffPolicy.backOff(backOffContext);
} catch (BackOffInterruptedException ex) {
lastException = e;
// back off was prevented by another thread - fail the retry
if (logger.isDebugEnabled()) {
logger.debug("Abort retry because interrupted: count={}", context.getRetryCount());
}
throw ex;
}
}
if (logger.isDebugEnabled()) {
logger.debug("Checking for rethrow: count={}", context.getRetryCount());
}
if (shouldRethrow(retryPolicy, context, state)) {
if (logger.isDebugEnabled()) {
logger.debug("Rethrow in retry for policy: count={}", context.getRetryCount());
}
throw RetryTemplate.<E>wrapIfNecessary(e);
}
}
/*
* A stateful attempt that can retry may rethrow the exception before now,
* but if we get this far in a stateful retry there's a reason for it,
* like a circuit breaker or a rollback classifier.
*/
if (state != null && context.hasAttribute(GLOBAL_STATE)) {
break;
}
}
if (state == null && logger.isDebugEnabled()) {
logger.debug("Retry failed last attempt: count={}", context.getRetryCount());
}
exhausted = true;
return handleRetryExhausted(recoveryCallback, context, state);
} catch (Throwable e) {
throw RetryTemplate.<E>wrapIfNecessary(e);
} finally {
close(retryPolicy, context, state, lastException == null || exhausted);
doCloseInterceptors(retryCallback, context, lastException);
RetrySynchronizationManager.clear();
}
}
use of cn.taketoday.retry.RetryContext in project today-infrastructure by TAKETODAY.
the class RetryListenerTests method testOpenCanVetoRetry.
@Test
public void testOpenCanVetoRetry() throws Throwable {
template.registerListener(new RetryListener() {
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
list.add("1");
return false;
}
});
try {
template.execute(new RetryCallback<String, Exception>() {
public String doWithRetry(RetryContext context) throws Exception {
count++;
return null;
}
});
fail("Expected TerminatedRetryException");
} catch (TerminatedRetryException e) {
// expected
}
assertEquals(0, count);
assertEquals(1, list.size());
assertEquals("1", list.get(0));
}
use of cn.taketoday.retry.RetryContext in project today-infrastructure by TAKETODAY.
the class ExceptionClassifierRetryPolicyTests method testNullPolicies.
@Test
public void testNullPolicies() throws Exception {
policy.setPolicyMap(new HashMap<Class<? extends Throwable>, RetryPolicy>());
RetryContext context = policy.open(null);
assertNotNull(context);
}
use of cn.taketoday.retry.RetryContext in project today-infrastructure by TAKETODAY.
the class ExceptionClassifierRetryPolicyTests method testRetryCount.
@Test
public void testRetryCount() throws Exception {
ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy();
RetryContext context = policy.open(null);
assertNotNull(context);
policy.registerThrowable(context, null);
assertEquals(0, context.getRetryCount());
policy.registerThrowable(context, new RuntimeException("foo"));
assertEquals(1, context.getRetryCount());
assertEquals("foo", context.getLastThrowable().getMessage());
}
Aggregations