春季重试,无需春季申请 [英] Spring retry without spring application
问题描述
我有一个Java应用程序,它从主类开始(不是Spring Boot应用程序).我想使用Spring retry在连接丢失时重试. 据我所知,我需要在Spring应用程序的主类上方添加@EnableRetry批注,然后在我的方法上方使用@Retryable进行重试.但是我认为这在非Spring应用程序中将不起作用. 是否可以在简单的Java应用程序(而非spring应用程序)中使用spring retry?
I have a java application, which starts from the main class (not Spring boot application). And I want to use Spring retry to retry when a connection is lost. As I know I need to add @EnableRetry annotation above main class in Spring application and then use @Retryable above my method with retrying. But I think it will not work in the non-spring application. Is it possible to use spring retry in simple java application (not spring app)?
推荐答案
我发现我可以使用RetryTemplate:
I found that I can use RetryTemplate:
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(2000l);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(5);
retryTemplate.setRetryPolicy(retryPolicy);
retryTemplate.execute(new RetryCallback<Void, Throwable>() {
@Override
public Void doWithRetry(RetryContext context) throws Throwable {
// do some job
if(context.getRetryCount() < 3){ // unexpected disconnection
log.error("connection failed");
throw new RuntimeException("retry exception");
}
System.out.println("RETRY" + context);
return null;
}
});
这篇关于春季重试,无需春季申请的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!