作用于调用某个服务,如果没有正常获取服务就会循环调用的情况,直到服务正常调用成功。
1.引入依赖
<!--spring-retry-->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
2.启动类启用spring-retry
@EnableRetry
@SpringBootApplication
public class LimitProjectApplication {
public static void main(String[] args) {
SpringApplication.run(LimitProjectApplication.class, args);
}
}
3.在服务层方法添加@Retryable注解 表明要重试的地方
/**
* @author qinxun
* @date 2023-04-26
* @Descripion: 重试测试服务类
*/
@Slf4j
@Service
public class RetryService {
/*
* @Retryable 重试注解参数说明
* value: 抛出指定的异常才会重试操作
* maxAttempts: 最大重试次数 默认为3次
* backoff: 重试等待策略 @Backoff value默认1000L 1秒重试一次
*/
@Retryable(value = Exception.class, backoff = @Backoff(value = 2000L))
public Integer retry(Integer code) throws Exception {
log.info("testRetry被调用");
if (code <= 0) {
throw new Exception("数据出现异常");
}
System.out.println("数据正常");
return code;
}
/*
* @Recover 注解的方法表示重试次数用完后会回调的方法
*/
@Recover
public Integer recover(Exception e, Integer code) {
log.info("回调被执行!!");
return 400;
}
}
4.创建控制层测试
/**
* @author qinxun
* @date 2023-04-26
* @Descripion: 测试重试 控制层
*/
@RestController
public class TestRetryController {
@Autowired
private RetryService retryService;
@GetMapping("/testRetry")
public Integer testRetry(Integer code) throws Exception {
return retryService.retry(code);
}
}
5.浏览器测试 http://localhost:8080/testRetry?code=0
2023-04-26 14:42:12.107 INFO 20108 --- [nio-8080-exec-1] o.apache.tomcat.util.http.parser.Cookie : A cookie header was received [This is username=admin;] that contained an invalid cookie. That cookie will be ignored.
Note: further occurrences of this error will be logged at DEBUG level.
2023-04-26 14:42:12.109 INFO 20108 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2023-04-26 14:42:12.110 INFO 20108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2023-04-26 14:42:12.110 INFO 20108 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2023-04-26 14:42:12.135 INFO 20108 --- [nio-8080-exec-1] c.e.limitproject.service.RetryService : testRetry被调用
2023-04-26 14:42:14.139 INFO 20108 --- [nio-8080-exec-1] c.e.limitproject.service.RetryService : testRetry被调用
2023-04-26 14:42:16.142 INFO 20108 --- [nio-8080-exec-1] c.e.limitproject.service.RetryService : testRetry被调用
2023-04-26 14:42:16.145 INFO 20108 --- [nio-8080-exec-1] c.e.limitproject.service.RetryService : 回调被执行!!
可以看到平均2秒钟调用一次重试的方法,如果重试的次数用尽,就会回调@Recover注解里的方法。