Search in sources :

Example 6 with RetryPolicy

use of cn.taketoday.retry.RetryPolicy in project today-framework 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();
    }
}
Also used : BackOffPolicy(cn.taketoday.retry.backoff.BackOffPolicy) NoBackOffPolicy(cn.taketoday.retry.backoff.NoBackOffPolicy) BackOffContext(cn.taketoday.retry.backoff.BackOffContext) RetryContext(cn.taketoday.retry.RetryContext) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryPolicy(cn.taketoday.retry.RetryPolicy) SimpleRetryPolicy(cn.taketoday.retry.policy.SimpleRetryPolicy) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException) ExhaustedRetryException(cn.taketoday.retry.ExhaustedRetryException) BackOffInterruptedException(cn.taketoday.retry.backoff.BackOffInterruptedException) RetryException(cn.taketoday.retry.RetryException) TerminatedRetryException(cn.taketoday.retry.TerminatedRetryException)

Example 7 with RetryPolicy

use of cn.taketoday.retry.RetryPolicy in project today-framework by TAKETODAY.

the class ExceptionClassifierRetryPolicy method close.

/**
 * Delegate to the policy currently activated in the context.
 *
 * @see RetryPolicy#close(RetryContext)
 */
public void close(RetryContext context) {
    RetryPolicy policy = (RetryPolicy) context;
    policy.close(context);
}
Also used : RetryPolicy(cn.taketoday.retry.RetryPolicy)

Example 8 with RetryPolicy

use of cn.taketoday.retry.RetryPolicy in project today-framework 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);
}
Also used : RetryContext(cn.taketoday.retry.RetryContext) RetryPolicy(cn.taketoday.retry.RetryPolicy) Test(org.junit.Test)

Example 9 with RetryPolicy

use of cn.taketoday.retry.RetryPolicy in project today-framework by TAKETODAY.

the class ExceptionClassifierRetryPolicyTests method testClassifierOperates.

@SuppressWarnings("serial")
@Test
public void testClassifierOperates() throws Exception {
    RetryContext context = policy.open(null);
    assertNotNull(context);
    assertTrue(policy.canRetry(context));
    policy.registerThrowable(context, new IllegalArgumentException());
    // NeverRetryPolicy is the
    assertFalse(policy.canRetry(context));
    // default
    policy.setExceptionClassifier(new Classifier<Throwable, RetryPolicy>() {

        public RetryPolicy classify(Throwable throwable) {
            if (throwable != null) {
                return new AlwaysRetryPolicy();
            }
            return new NeverRetryPolicy();
        }
    });
    // The context saves the classifier, so changing it now has no effect
    assertFalse(policy.canRetry(context));
    policy.registerThrowable(context, new IllegalArgumentException());
    assertFalse(policy.canRetry(context));
    // But now the classifier will be active in the new context...
    context = policy.open(null);
    assertTrue(policy.canRetry(context));
    policy.registerThrowable(context, new IllegalArgumentException());
    assertTrue(policy.canRetry(context));
}
Also used : RetryContext(cn.taketoday.retry.RetryContext) RetryPolicy(cn.taketoday.retry.RetryPolicy) Test(org.junit.Test)

Example 10 with RetryPolicy

use of cn.taketoday.retry.RetryPolicy in project today-framework by TAKETODAY.

the class AnnotationAwareRetryOperationsInterceptor method getStatefulInterceptor.

private MethodInterceptor getStatefulInterceptor(Object target, Method method, Retryable retryable) {
    RetryTemplate template = createTemplate(retryable.listeners());
    template.setRetryContextCache(this.retryContextCache);
    CircuitBreaker circuit = AnnotatedElementUtils.findMergedAnnotation(method, CircuitBreaker.class);
    if (circuit == null) {
        circuit = findAnnotationOnTarget(target, method, CircuitBreaker.class);
    }
    if (circuit != null) {
        RetryPolicy policy = getRetryPolicy(circuit);
        CircuitBreakerRetryPolicy breaker = new CircuitBreakerRetryPolicy(policy);
        breaker.setOpenTimeout(getOpenTimeout(circuit));
        breaker.setResetTimeout(getResetTimeout(circuit));
        template.setRetryPolicy(breaker);
        template.setBackOffPolicy(new NoBackOffPolicy());
        String label = circuit.label();
        if (!StringUtils.hasText(label)) {
            label = method.toGenericString();
        }
        return RetryInterceptorBuilder.circuitBreaker().keyGenerator(new FixedKeyGenerator("circuit")).retryOperations(template).recoverer(getRecoverer(target, method)).label(label).build();
    }
    RetryPolicy policy = getRetryPolicy(retryable);
    template.setRetryPolicy(policy);
    template.setBackOffPolicy(getBackoffPolicy(retryable.backoff()));
    String label = retryable.label();
    return RetryInterceptorBuilder.stateful().keyGenerator(this.methodArgumentsKeyGenerator).newMethodArgumentsIdentifier(this.newMethodArgumentsIdentifier).retryOperations(template).label(label).recoverer(getRecoverer(target, method)).build();
}
Also used : FixedKeyGenerator(cn.taketoday.retry.interceptor.FixedKeyGenerator) RetryTemplate(cn.taketoday.retry.support.RetryTemplate) NoBackOffPolicy(cn.taketoday.retry.backoff.NoBackOffPolicy) CircuitBreakerRetryPolicy(cn.taketoday.retry.policy.CircuitBreakerRetryPolicy) RetryPolicy(cn.taketoday.retry.RetryPolicy) ExpressionRetryPolicy(cn.taketoday.retry.policy.ExpressionRetryPolicy) SimpleRetryPolicy(cn.taketoday.retry.policy.SimpleRetryPolicy) CircuitBreakerRetryPolicy(cn.taketoday.retry.policy.CircuitBreakerRetryPolicy)

Aggregations

RetryPolicy (cn.taketoday.retry.RetryPolicy)20 RetryContext (cn.taketoday.retry.RetryContext)12 Test (org.junit.Test)12 SimpleRetryPolicy (cn.taketoday.retry.policy.SimpleRetryPolicy)8 ExhaustedRetryException (cn.taketoday.retry.ExhaustedRetryException)6 RetryException (cn.taketoday.retry.RetryException)6 DataAccessException (cn.taketoday.dao.DataAccessException)4 RetryCallback (cn.taketoday.retry.RetryCallback)4 RetryState (cn.taketoday.retry.RetryState)4 NoBackOffPolicy (cn.taketoday.retry.backoff.NoBackOffPolicy)4 NeverRetryPolicy (cn.taketoday.retry.policy.NeverRetryPolicy)4 TerminatedRetryException (cn.taketoday.retry.TerminatedRetryException)2 BackOffContext (cn.taketoday.retry.backoff.BackOffContext)2 BackOffInterruptedException (cn.taketoday.retry.backoff.BackOffInterruptedException)2 BackOffPolicy (cn.taketoday.retry.backoff.BackOffPolicy)2 RetryContextSupport (cn.taketoday.retry.context.RetryContextSupport)2 FixedKeyGenerator (cn.taketoday.retry.interceptor.FixedKeyGenerator)2 AlwaysRetryPolicy (cn.taketoday.retry.policy.AlwaysRetryPolicy)2 BinaryExceptionClassifierRetryPolicy (cn.taketoday.retry.policy.BinaryExceptionClassifierRetryPolicy)2 CircuitBreakerRetryPolicy (cn.taketoday.retry.policy.CircuitBreakerRetryPolicy)2