1. pom.xml
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId >
<artifactId>aspectjweaver</artifactId >
<version>1.6.11</version >
</dependency>
2. 启动类Application
添加 @EnableRetry 注解
@SpringBootApplication
@EnableRetry
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3. Service
public interface MyService {
public String retryTest(int code) throws Exception;
}
4. ServiceImpl
@Service
@Slf4j
public class MyServiceImpl implements MyService {
@Override
@Retryable(value=Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 2))
public String retryTest(int code) throws Exception {
log.info("{} :running",LocalTime.now());
if(code < 5){
log.error("{} :retry {}",LocalTime.now(),code);
throw new Exception("running exception !!");
}
return "success";
}
/**
* 重试次数耗尽后的处理
* 可以记日志或者其他弥补措施
*/
@Recover
public String retryTestRecover(Exception e,int code){
log.error("done: error !!");
return "error";
}
}
@Retryable 和 @Transactional 注解比较类似;
- value: 触发重试的异常条件
- maxAttempts: 最大重试次数
- backoff :重试机制(delay :延时多久重试,multiplier :每次重试延时时间翻倍数)
@Recover 注解的重试次数耗尽方法返回值与参数中的异常类需要与@Retryable的返回值与抛出的异常类一致!!
5. Controller
@RestController
@RequestMapping("/test")
public class MyController {
@Autowired
MyService myService;
@GetMapping("retry")
public String testRetry() throws Exception{
return myService.retryTest(1);
}
}
6. 验证
启动程序,访问 http://localhost:8080/test/retry
2021-12-10 08:52:39.038 INFO 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:39.038 :running
2021-12-10 08:52:39.039 ERROR 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:39.039 :retry 1
2021-12-10 08:52:41.044 INFO 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:41.044 :running
2021-12-10 08:52:41.046 ERROR 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:41.046 :retry 1
2021-12-10 08:52:45.048 INFO 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:45.048 :running
2021-12-10 08:52:45.050 ERROR 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : 08:52:45.050 :retry 1
2021-12-10 08:52:45.052 ERROR 20312 --- [nio-8000-exec-1] c.e.demo.service.impl.MyServiceImpl : done: error !!