在微服务中使用Spring-Retry

  • Spring-Retry为Spring应用程序提供声明式重试机制。在微服务架构中,服务之间的调用会依赖网络,或者在调用第三方接口或者使用mq时,会出现网络抖动,连接超时等网络异常,所以需要重试。
  • Spring-Boot项目使用Spring-Retry非常简单,在配置类加上@EnableRetry注解启用spring-retry,然后在需要失败重试的方法加@Retryable注解即可,Spring-Retry通过捕获异常来触发重试机制。为了使处理更加健壮并且不太容易出现故障,后续的尝试操作,有时候会帮助失败的操作最后执行成功。
Maven依赖
	<dependency>
      <groupId>org.springframework.retry</groupId>
      <artifactId>spring-retry</artifactId>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
    </dependency>
入口类

需要在程序入口加@EnableRetry注解。


@SpringBootApplication
@EnableRetry
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Service类
@Service
@Slf4j
public class RetryService {

    @Retryable(value = Exception.class, maxAttempts = 5, backoff = @Backoff(delay = 2000L, multiplier = 1.5))
    public void retry() throws Exception {
        log.info("retry" + LocalTime.now());
        throw new RemoteAccessException("RemoteAccessException....");
    }
    
	@Recover
    public void recover(RemoteAccessException e) {
        log.info("error message is" + e.getMessage());
        log.info("recover....");
    }
}
Test类
@SpringBootTest
class DemoApplicationTests {

	@Autowired
	private RetryService retryService;

	@Test
	public void reteyTest() throws Exception {
		retryService.retry();
	}

}
打印结果

在这里插入图片描述

参数说明
  • @EnableRetry能否重试。在spring-Boot中此参数写在程序入口即可。
  • @Retryable
    • value:需要进行重试的异常,和参数includes是一个意思。默认为空,当参数exclude也为空时,所有异常都将要求重试。
    • include:需要进行重试的异常,默认为空。当参数exclude也为空时,所有异常都将要求重试。
    • exclude:不需要重试的异常。默认为空,当参include也为空时,所有异常都将要求重试。
    • stateful:标明重试是否是有状态的,异常引发事物失效的时候需要注意这个。该参数默认为false。远程方法调用的时候不需要设置,因为远程方法调用是没有事物的;只有当数据库更新操作的时候需要设置该值为true,特别是使用Hibernate的时候。抛出异常时,异常会往外抛,使事物回滚;重试的时候会启用一个新的有效的事物。
    • maxAttempts:最大重试次数,默认为3。包括第一次失败。
    • backoff:回避策略,默认为空。该参数为空时是,失败立即重试,重试的时候阻塞线程。
  • @Recover:该注解用于恢复处理方法,当全部尝试都失败时执行。返回参数必须和@Retryable修饰的方法返回参数完全一样。第一个参数必须是异常,其他参数和@Retryable修饰的方法参数顺序一致。
  • @Backoff
    • value:重试延迟时间,单位毫秒,默认值1000,即默认延迟1秒。当未设置multiplier时,表示每隔value的时间重试,直到重试次数到达maxAttempts设置的最大允许重试次数。当设置了multiplier参数时,该值作为幂运算的初始值。等同delay参数,两个参数设置一个即可。
    • delay:等同value
    • maxDelay:两次重试间最大间隔时间。当设置multiplier参数后,下次延迟时间根据是上次延迟时间乘以multiplier得出的,这会导致两次重试间的延迟时间越来越长,该参数限制两次重试的最大间隔时间,当间隔时间大于该值时,计算出的间隔时间将会被忽略,使用上次的重试间隔时间。
    • multiplier:作为乘数用于计算下次延迟时间。公式:delay = delay * multiplier
  • dsa
注意的地方
  • 使用了@Retryable的方法里面不能使用try…catch包裹,要在方法上抛出异常,不然不会触发。
发布了142 篇原创文章 · 获赞 89 · 访问量 27万+

猜你喜欢

转载自blog.csdn.net/wangchengming1/article/details/102839667