我正在使用 spring 重试模板实现重试逻辑,该模板需要重试所有异常,但排除我在某种条件下抛出的异常。 但是,spring 也会重试该异常,但我无法更改它。
这是我的方法,其中 someException 继承自 BroadException:
@Retryable(noRetryFor = {SomeException.class}, maxAttempts = 4, backoff = @Backoff(delayExpression = "${retry.delay:2000}", multiplier = 2))
@Override
public void someMethod(String id) throws broadException{
Optional<Object> object = repository.getObject(id);
if (object.isPresent()) {
//do stuff
}
else{
throw new SomeException();
}
}
为什么 spring 忽略我的“noRetryFor”?
我尝试删除 SomeException.class 周围的括号,但没有什么区别。
最佳答案
这对我来说效果很好 -
2.0.0:
@SpringBootApplication
@EnableRetry
public class So75502613Application {
public static void main(String[] args) {
SpringApplication.run(So75502613Application.class, args);
}
@Bean
ApplicationRunner runner(Foo foo) {
return args -> {
foo.doIt("fail");
foo.doIt("someEx");
};
}
}
@Component
class Foo {
@Retryable(noRetryFor = SomeException.class)
void doIt(String in) {
System.out.println(in);
if ("someEx".equals(in)) {
throw new SomeException();
}
throw new IllegalStateException();
}
@Recover
void recover(Exception ex, String in) {
System.out.println(in + ":" + ex.getClass().getSimpleName());
}
}
@SuppressWarnings("serial")
class SomeException extends RuntimeException {
}
fail
fail
fail
fail:IllegalStateException
someEx
someEx:SomeException
1.3.4:
@SpringBootApplication
@EnableRetry
public class So75502613Application {
public static void main(String[] args) {
SpringApplication.run(So75502613Application.class, args);
}
@Bean
ApplicationRunner runner(Foo foo) {
return args -> {
foo.doIt("fail");
foo.doIt("someEx");
};
}
}
@Component
class Foo {
@Retryable(exclude = SomeException.class)
void doIt(String in) {
System.out.println(in);
if ("someEx".equals(in)) {
throw new SomeException();
}
throw new IllegalStateException();
}
@Recover
void recover(Exception ex, String in) {
System.out.println(in + ":" + ex.getClass().getSimpleName());
}
}
@SuppressWarnings("serial")
class SomeException extends RuntimeException {
}
fail
fail
fail
fail:IllegalStateException
someEx
someEx:SomeException
关于java - Spring Retry忽略 "noRetryFor"(重试所有异常),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75502613/