如何解决Spring Boot @Retryable maxAttempts根据异常
我想知道有关Spring Boot @Retryable
注释的事情。
我想根据异常类型实现@Retryable
maxAttemps计数,例如:
if Exception type is ExceptionA:
@Retryable(value = ExceptionA.class,maxAttempts = 2)
if Exception type is ExceptionB:
@Retryable(value = ExceptionB.class,maxAttempts = 5)
是否可以使用@Retryable
注释,或者有任何建议吗?
解决方法
不直接;您将必须构造一个自定义拦截器(RetryInterceptorBuilder
)bean,并在@Retryable.interceptor
中提供其bean名称。
使用ExceptionClassifierRetryPolicy
对每个异常使用不同的策略。
编辑
这是一个例子:
@SpringBootApplication
@EnableRetry
public class So64029544Application {
public static void main(String[] args) {
SpringApplication.run(So64029544Application.class,args);
}
@Bean
public ApplicationRunner runner(Retryer retryer) {
return args -> {
retryer.toRetry("state");
retryer.toRetry("arg");
};
}
@Bean
public Object retryInterceptor(Retryer retryer) throws Exception {
ExceptionClassifierRetryPolicy policy = new ExceptionClassifierRetryPolicy();
policy.setPolicyMap(Map.of(
IllegalStateException.class,new SimpleRetryPolicy(2),IllegalArgumentException.class,new SimpleRetryPolicy(3)));
Method recover = retryer.getClass().getDeclaredMethod("recover",Exception.class);
return RetryInterceptorBuilder.stateless()
.retryPolicy(policy)
.backOffOptions(1_000,1.5,10_000)
.recoverer(new RecoverAnnotationRecoveryHandler<>(retryer,recover))
.build();
}
}
@Component
class Retryer {
@Retryable(interceptor = "retryInterceptor")
public void toRetry(String in) {
System.out.println(in);
if ("state".equals(in)) {
throw new IllegalStateException();
}
else {
throw new IllegalArgumentException();
}
}
@Recover
public void recover(Exception ex) {
System.out.println("Recovered from " + ex
+ ",retry count:" + RetrySynchronizationManager.getContext().getRetryCount());
}
}
state
state
Recovered from java.lang.IllegalStateException,retry count:2
arg
arg
arg
Recovered from java.lang.IllegalArgumentException,retry count:3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。