首页 > 解决方案 > Spring Retry maxAttempts 不起作用

问题描述

一个非常简单的 HelloWorld 测试

@Log4j2
@Service
@EnableRetry
@EnableScheduling
public class MyBeanImpl {
    @Scheduled(cron = "0/2 * *  * * ? ")
    @Retryable(value = {RuntimeException.class}, maxAttempts = 4, backoff = @Backoff(delay = 10000))
    public void sched() {
        log.info("Foo sched a = {}", a++);
        throw new RuntimeException("Foo");
    }    
}


@Recover
public void recover(RuntimeException e) {
//.....
}

// Junit Class is here , For Simple POC test, I dont use Interface class, just use Implementation class
@RunWith(SpringRunner.class)
@SpringBootTest
@Log4j2
@ContextConfiguration
public class MyBeanImplTest {
@Autowired    
MyBeanImpl _myBean;

private String input = "HelloWorld";

@Test
public void sched() {
_myBean.sched();
}

问题 :

我设置 maxAttempts = 1,它运行 1 次。为什么?

我设置 maxAttempts = 2,它总是运行 3 次。为什么?

我设置了 maxAttempts = 4,但是它运行了 8 次。为什么?

我设置 maxAttempts = 6,它运行了 11 次。为什么?

标签: spring-bootspring-retry

解决方案


可能是因为它被计划以及被测试用例调用。

查看 INFO 日志中的线程名称。


推荐阅读