好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

spring retry方法调用失败重试机制示例解析

前言

很多场景会用到重试的机制,比如:rpc服务调用失败重试,文件上传oss失败重试,http接口调用失败重试,支付回调失败重试等等,一切因为网络,非逻辑性错误等不确定因素引起的失败都可以加上重试的机制,来增强系统的健壮性,博主也处理过文件上传到第三方oss服务失败增加重试的事例,在这之前不知道spring有个spring-retry项目,所以采用的是限制次数的递归调用的方式来解决的。

现在我们来看看spring boot项目中怎么使用spring-retry来处理是失败重试的问题。

1.导入依赖

?

1

2

3

4

5

6

7

8

< 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.注解的使用

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

/**

      * @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.开启重试

?

1

2

3

4

5

6

7

@SpringBootApplication

@EnableRetry

public class BootRetryApplication {

     public static void main(String[] args) {

         SpringApplication.run(BootRetryApplication. class , args);

     }

}

ps:别忘了@EnableRetry注解开启重试

github项目地址: https://github测试数据/spring-projects/spring-retry

补充,手动声明式重试:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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();

     }

以上就是spring retry方法调用失败重试机制示例解析的详细内容,更多关于spring retry方法调用失败重试机制的资料请关注其它相关文章!

原文链接:http://HdhCmsTestkailing.pub/article/index/arcid/147.html

查看更多关于spring retry方法调用失败重试机制示例解析的详细内容...

  阅读:12次