前言碎语
很多场景会用到重试的机制,比如:rpc服务调用失败重试,文件上传oss失败重试,http接口调用失败重试,支付回调失败重试等等,一切因为网络,非逻辑性错误等不确定因素引起的失败都可以加上重试的机制,来增强系统的健壮性,博主也处理过文件上传到第三方oss服务失败增加重试的事例,在这之前不知道spring有个spring-retry项目,所以采用的是限制次数的递归调用的方式来解决的。现在我们来看看spring boot项目中怎么使用spring-retry来处理是失败重试的问题
1.导入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> </dependency>
ps:不要遗漏spring-boot-starter-aop包
2.注解的使用
/** * @Retryable注解参数说明 * maxAttempts 重试的次数 * value 指定异常重试 * exclude 排除某个异常不重试 * * @Backoff注解参数说明 * backoff 重试的间隔时间 */ @Retryable(maxAttempts=9,exclude = ArrayIndexOutOfBoundsException.class,value=Exception.class,backoff=@Backoff(delay = 1000)) public String getResult(String name){ System.out.println("尝试调用第"+i+++"次"); name= name.split(",")[1111];//异常测试 if(i!=8){ name= name.split(",")[1111];//异常测试 } return name+":你好!"; }3.开启重试
@SpringBootApplication @EnableRetry public class BootRetryApplication { public static void main(String[] args) { SpringApplication.run(BootRetryApplication.class, args); } }ps:别忘了@EnableRetry注解开启重试
github项目地址:https://github.com/spring-projects/spring-retry
2018/3/20补充,手动声明式重试:
public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(HelloService.class.getClassLoader()); factory.setInterfaces(HelloService.class); factory.setTarget(new HelloService() { @Override public String say() { System.err.println("hello"); if(1==1) throw new SecurityException(); return "a"; } }); HelloService service = (HelloService) factory.getProxy(); JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut(); pointcut.setPatterns(".*say.*"); RetryOperationsInterceptor interceptor = new RetryOperationsInterceptor(); ((Advised) service).addAdvisor(new DefaultPointcutAdvisor(pointcut, interceptor)); service.say(); }