<!-- 重试机制 -->
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
/**
* value:抛出指定异常才会重试
* include:和value一样,默认为空,当exclude也为空时,默认所有异常
* exclude:指定不处理的异常
* maxAttempts:最大重试次数,默认3次
* backoff:重试等待策略,
* 默认使用@Backoff,@Backoff的value默认为1000L,我们设置为2000; 以毫秒为单位的延迟(默认 1000)
* multiplier(指定延迟倍数)默认为0,表示固定暂停1秒后进行重试,如果把multiplier设置为1.5,则第一次重试为2秒,第二次为 [1.5 * 2 = 3] 秒,第三次为 [ 3 * 1.5 = 4.5 ]秒。
* @param code
* @return
* @throws Exception
*/
@Retryable(value = Exception.class,maxAttempts = 3,backoff = @Backoff(delay = 2000,multiplier = 1.5),recover = "recover1")
@RequestMapping("retryTest")
public String retryTest(String code) {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+" ,重试机制,"+code);
if(true){
throw new RuntimeException();
}
return "1";
}
//Spring-Retry还提供了@Recover注解,用于@Retryable重试失败后处理方法。如果不需要回调方法,可以直接不写回调方法,那么实现的效果是,重试次数完了后,如果还是没成功没符合业务判断,就抛出异常。
// @Recover 方法 注意:第一个参数为报错异常信息,其他参数与返回类型必须和要进行回调的方法一致,此处必须和retryTest方法的入参和返回值类型一致,如果有多个就通过 @Retryable 中的 recover =“xx” 指定好。
@Recover
public String recover(Exception e,String code)
{
System.out.println("重试次数耗尽,错误信息入库,进行后续补偿操作!");
return "0";
}
@Recover
public String recover1(Exception e,String code)
{
System.out.println("1重试次数耗尽,错误信息入库,进行后续补偿操作!");
return "0";
}