Spring retry find the last retry

亡梦爱人 提交于 2020-12-01 14:55:53

问题


I am using Spring-retry-1.2.0, Retry is working fine, but in my method i want to find it out whether the retrial is the last retrial or not, Is there any method available to get the retrialCount or last retrial in spring-retry?

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();
}
}

Changes made after Artem Bilan comments

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...

}

Any help would be appreciable.


回答1:


I think what you need is called @Recover (RecoveryCallback if without annotations):

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

See the same README and test-case on the matter.




回答2:


If you are manually creating/using RetryTemplate's, you can get the current retry count from RetryContext as follows:

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();
        }
    });
}


来源:https://stackoverflow.com/questions/42977385/spring-retry-find-the-last-retry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!