Spring重试支持Spring Retry的方法
本文介绍了Spring重试支持Spring Retry的方法,分享给大家,具体如下: 第一步、引入maven依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.3.RELEASE</version> </parent> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.retry/spring-retry --> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.1.2.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.6</version> </dependency> 第二步、添加@Retryable和@Recover注解 package hello; import org.springframework.remoting.RemoteAccessException; import org.springframework.retry.annotation.Backoff; import org.springframework.retry.annotation.Recover; import org.springframework.retry.annotation.Retryable; import org.springframework.stereotype.Service; @Service public class RemoteService { @Retryable(value= {RemoteAccessException.class},maxAttempts = 3,backoff = @Backoff(delay = 5000l,multiplier = 1)) public void call() throws Exception { System.out.println("do something..."); throw new RemoteAccessException("RPC调用异常"); } @Recover public void recover(RemoteAccessException e) { System.out.println(e.getMessage()); } } @Retryable注解 @Backoff注解 @Recover 第三步、SpringBoot方式启动容器、测试 添加@EnableRetry注解,启用重试功能 package hello; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.retry.annotation.EnableRetry; @SpringBootApplication @EnableRetry public class Application { public static void main(String[] args) throws Exception { ApplicationContext annotationContext = new AnnotationConfigApplicationContext("hello"); RemoteService remoteService = annotationContext.getBean("remoteService",RemoteService.class); remoteService.call(); } } 运行结果:
参考 :https://github.com/spring-projects/spring-retry 补充 对于非幂等的请求(比如新增,更新操作),千万不要使用重试,对数据一致性会造成很大影响。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 您可能感兴趣的文章:
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |