Spring重试找到最后的重试

时间:2017-03-23 13:24:58

标签: spring spring-mvc spring-integration spring-retry

我正在使用Spring-retry-1.2.0,Retry工作正常,但在我的方法中我想知道重审是否是最后一次重审,是否有任何方法可以获得retrialCount或最后重审弹簧重试吗?

Retrial.java

public class Offers extends SimpleRetryPolicy {

@Async
@Retryable(maxAttemptsExpression = "#{retrial.times}", backoff = @Backoff(delayExpression = "#{retrial.delay}"))
public void handleOfferes(Data data) {

 AlwaysRetryPolicy policy = new AlwaysRetryPolicy();
        RetryContext context = policy.open(null);
        System.out.println("context.getRetryCount()::"+context.getRetryCount()); //Always logs 0 even if it retries 2 to 3 times...
        System.out.println("Can retry::"+canRetry(context)); //Always true
//Business Logic
//Get the last count and update the DB ...retrial is ends with failure
}


@Override
public boolean canRetry(RetryContext context) {
    System.out.println("context.getRetryCount()::"+context.getRetryCount());
    System.out.println("getMaxAttempts::"+getMaxAttempts());
    return context.getRetryCount() < getMaxAttempts();
}
}

Artem Bilan评论后发生的变化

RetryConfiguration

@Configuration
public class RetryConfiguration {

@Value("${retrial.times}")
private Long delayExpression;

@Value("${retrial.delay}")
private int maxAttempts;

@Bean
@ConditionalOnMissingBean(name = "retryInterceptor")
public RetryOperationsInterceptor retryInterceptor() {
    return RetryInterceptorBuilder
            .stateless()
            .backOffOptions(0L,
                    0.0D, delayExpression)
            .maxAttempts(maxAttempts).build();
}
}

Offers.java

@Service
public class Offers {
@Async
@Retryable(interceptor = "retryInterceptor")
public void handleDeviceStatus(Data data) {
//Here how shall i get the retrial count...

}

任何帮助都会很明显。

2 个答案:

答案 0 :(得分:4)

如果您手动创建/使用RetryTemplate,您可以从RetryContext获取当前重试次数,如下所示:

public String callWithRetry() {
    return retryTemplate.execute(new RetryCallback<String, RuntimeException>() {
        @Override
        public String doWithRetry(RetryContext context) {
            LOG.info("Retry count: {}", context.getRetryCount());
            return theService.perform();
        }
    });
}

答案 1 :(得分:3)

我认为您需要的是@Recover(如果没有注释,则为RecoveryCallback):

@Retryable(RemoteAccessException.class)
public void service() {
    // ... do something
}
@Recover
public void recover(RemoteAccessException e) {
   // ... panic
}

在此问题上看到相同的READMEtest-case