iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >spring retry方法调用失败重试机制示例解析
  • 947
分享到

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

2024-04-02 19:04:59 947人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录前言1.导入依赖2.注解的使用3.开启重试补充,手动声明式重试:前言 很多场景会用到重试的机制,比如:rpc服务调用失败重试,文件上传oss失败重试,Http接口调用失败重试,支

前言

很多场景会用到重试的机制,比如: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=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

补充,手动声明式重试:

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方法调用失败重试机制的资料请关注编程网其它相关文章!

--结束END--

本文标题: spring retry方法调用失败重试机制示例解析

本文链接: https://www.lsjlt.com/news/141423.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作