spring-retry失败重试

spring-retry实现重试功能

  • POM 依赖
  • 启用Retryable
  • 在需要重试的方法上添加@Retryable注解
    • @Retryable参数
    • @Recover注意事项

spring-retry官网地址
在实际开发中,我们可能有重试的需要。这里使用springboot集成spring-retry实现重试功能
如: 1、网络波动需要,导致请求失败,需要重发。
        2、发送消息失败,需要重发,重发失败要记录日志
        …

POM 依赖

<dependency>
  <groupId>org.springframework.retrygroupId>
  <artifactId>spring-retryartifactId>
dependency>


<dependency>
	<groupId>org.aspectjgroupId>
	<artifactId>aspectjrt artifactId>
	<version>1.8.0version>
dependency>
<dependency>
	<groupId >org.aspectjgroupId>
	<artifactId>aspectjweaverartifactId>
	<version>1.8.0version >
dependency>

启用Retryable

在启动类上添加@EnableRetry注解

@EnableRetry
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}

在需要重试的方法上添加@Retryable注解

如果有失败回调的需要在回调的方法上加@Retryable注解
注: 1、重试方法内不要使用 try catch抛出异常即可
        2、如果重试失败需要对@Recover注解的方法做后续处理,重试方法不能有返回值

@Service
public class MSGRetryServiceImpl implements MSGRetryService {

    @Override
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 2000,multiplier = 1.5))
    public int send(Message message) throws Exception{
        System.out.println("send被调用,时间:"+ LocalTime.now());
        if("0".equals(message.getMessage())){
            throw new RuntimeException("发送失败!");
        }else if("500".equals(message.getMessage())){
            throw new Exception("系统异常!");
        }
        System.out.println("消息发送成功!");
        return 200;
    }

    @Recover
    public int recoverSend(Exception e, Message message){
        System.out.println("Exception异常回调方法执行!!!!");
        System.out.println(message.toString());
        return 500;
    }

    @Recover
    public int recoverSend(RuntimeException e){
        System.out.println("RuntimeException异常回调方法执行!!!!");
        return 0;
    }

}

@Retryable参数

value:抛出指定异常重试
include:抛出指定异常重试,默认为空,当 exclude 也为空时,默认所有异常
exclude:不处理的异常
maxAttempts:最大重试次数,默认 3 次
backoff:重试等待策略,默认使用 @Backoff,@Backoff 的 value 默认为 1000L
multiplier:指定延迟倍数,默认为 0,表示固定暂停 1 秒后进行重试,如果把 multiplier 设置为 1.5,则第一次重试为 2 秒,第二次为 3 秒,第三次为 4.5 秒。

@Recover注意事项

  • 方法的返回值必须与 @Retryable 方法一致
  • 方法第一个参数,须是Throwable类型,建议与@Retryable配置的异常一致,其他的参数,按需添加
  • 回调方法与重试方法写在同一个实现类里

你可能感兴趣的:(实用技巧,失败重试,请求重试,重发,重试,方法重试)