springboot调用spring-retry:
配置依赖Maven:
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
启动类:
@SpringBootApplication
@EnableTransactionManagement // 启注解事务管理
@EnableScheduling
@EnableRetry // 【注意这里】启用了重试功能
public class TestWebApplication {
public static void main(String[] args) {
SpringApplication.run(TestWebApplication.class, args);
}
}
重试部分的代码:
@Service
public class RetryServiceImpl implements RetryService {
private static final Logger LOGGER = LoggerFactory.getLogger(RetryServiceImpl.class);
private AtomicInteger count = new AtomicInteger(1);
@Override
@Retryable(value = { RemoteAccessException.class }, maxAttemptsExpression = "${retry.maxAttempts:10}",
backoff = @Backoff(delayExpression = "${retry.backoff:1000}"))
public void retry() {
LOGGER.info("start to retry : " + count.getAndIncrement());
throw new RemoteAccessException("here " + count.get());
}
/*
@Recover 的用法。
它要求它注释的方法的返回值必须和@Retryable的注释的方法返回值保持一致,
否则@Recover 注释的方法不会被调用。它还有关于自己参数的使用要求。
*/
@Recover
public void recover(RemoteAccessException t) {
LOGGER.info("SampleRetryService.recover:{}", t.getClass().getName());
}
}
文章持续更新:欢迎各位小伙伴关注我的公众号:菜丸的程序屋。希望将我的不足之处给予指点,谢谢大家。喜欢Java,热衷学习的小伙伴可以加我微信: CaiWan_Y