我使用spring-retry模块使用以下RetryTemplate配置:
@EnableRetry
@Configuration
public class RetryConfig {
@Bean
public RetryTemplate retryTemplate() {
final FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(500);
final SimpleRetryPolicy attemptsPolicy = new SimpleRetryPolicy();
attemptsPolicy.setMaxAttempts(2);
final TimeoutRetryPolicy timeoutPolicy = new TimeoutRetryPolicy();
timeoutPolicy.setTimeout(2000);
final CompositeRetryPolicy retryPolicy = new CompositeRetryPolicy();
retryPolicy.setPolicies(new RetryPolicy[] {timeoutPolicy, attemptsPolicy});
final RetryTemplate template = new RetryTemplate();
template.setBackOffPolicy(backOffPolicy);
template.setRetryPolicy(retryPolicy);
return template;
}
}
但是TimeoutRetryPolicy(在CompositeRetryPolicy实例中使用)显然不起作用。
我正在注入RetryTemplate以使用SOAP服务,在某些情况下,它需要10秒以上的时间来响应。但是,通过配置,我认为它不应该超过4秒(2秒超时* 2次尝试)。 非常感谢你提前!
答案 0 :(得分:0)
我遇到了同样的问题,遗憾的是无法使用spring-retry解决。因此,我实现了自己的通用类: RetryTemplate.java (gist链接)。
它的使用非常简单:
try {
final int attempts = 2;
final long timeout = 2000;
final String foo = new RetryTemplate<String>(attempts, timeout).execute(() -> {
// Your retryable logic here!
return "Lorem ipsum";
});
} catch (RetryException retryExpectedError) {
// Your logic if the re-attempts is exceeded.
// Note: RetryException is a simple inheritance of RuntimeException.
}
虽然我没有实现控制退避,但这将是微不足道的。我希望它有所帮助!
答案 1 :(得分:0)
首先是测试服务
@Service
public class RetrySoapServiceImpl implements RetryCallback<YourClass, YourException>{
static private int i = 0;
@Retryable(
value = { YourException.class },
maxAttempts = 300 //Just an Example. Try it with 6.
@Override
public PartnerWertelistenResponse doWithRetry(RetryContext arg0) throws YourException {
System.out.println("Attempt "+i);
i++;
if (i<300) throw new YourException();
else {
System.out.println("No Exception");
return null;
}
}
}
现在是主代码。
RetryTemplate template = new RetryTemplate();
FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
backOffPolicy.setBackOffPeriod(5000); //You'll become mesages every 5 Seconds.
TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
policy.setTimeout(50000L); //you'll be back in 50 Seconds, so you schould'nt wait 300*5 Sec.
template.setRetryPolicy(policy); //It's the last point
template.setBackOffPolicy(backOffPolicy); //It's the time to repeat an attempt
try {
YourClass result2 = template.execute(new RetrySoapServiceImpl());
} catch (YourException e) {
System.out.println("parent Catch Attempt "+e.getClass().getName());
}
System.out.println("ready to return");