Spring retry基本使用

背景介绍

在实际工作过程中,重试是一个经常使用的手段。比如MQ发送消息失败,会采取重试手段,比如工程中使用RPC请求外部服务,可能因为网络
波动出现超时而采取重试手段......可以看见重试操作是非常常见的一种处理问题,系统设计的手段

而在之前我们项目中处理重拾操作依赖MQ自身的重试机制,但是这种机制不是很灵活,如果某些功能没有使用MQ的话,那么就不是那么方便了,而本文介绍的
Spring-Retry却能够以一种很优雅的方式解决这种问题,当然目前版本的Spring-retry还不是完美的,还是有待改进的.不过已经很不错了.

基本使用

  • 例子1

    @Configuration
    @EnableRetry
    public class Application {
    
        @Bean
        public Service service() {
            return new Service();
        }
    
    }
    
    @Service
    class Service {
        @Retryable(RemoteAccessException.class)
        public void service() {
            // ... do something
        }
        @Recover
        public void recover(RemoteAccessException e) {
           // ... panic
        }
    }
  • 例子2

    @org.springframework.stereotype.Service
    public class Service1 {
    
        @Retryable(value = {RemoteAccessException.class, RuntimeException.class},
                maxAttempts = 2,
                backoff = @Backoff(value = 2000))
        public void service() {
            System.out.println("do some things");
            // this exception will just trigger recover1, do not trigger recover3
            throw new RemoteAccessException("remote access exception");
            // this exception will just trigger recover2
    //        throw new RuntimeException("runtime exception");
    
    //        System.out.println("do another things");
        }
    
        // 如果使用注解的话,这个recover貌似只能写在本类中,我测试了如果将recover方法写在
        // recoverService中,好像找不到
    
        @Recover
        public void recover1(RemoteAccessException e) {
            System.out.println(e.getMessage());
            System.out.println("do recover operation1");
        }
    
        @Recover
        public void recover2(RuntimeException e) {
            System.out.println(e.getMessage());
            System.out.println("do recover operation2");
        }
    
        @Recover
        public void recover3(RemoteAccessException e) {
            System.out.println(e.getMessage());
            System.out.println("do recover operation3");
        }
    
    }
  • 例子3

    @Service
    public class Service2 {
    
        public void test(){
            final RetryTemplate retryTemplate = new RetryTemplate();
            final SimpleRetryPolicy policy = new SimpleRetryPolicy(3, Collections.<Class<? extends Throwable>, Boolean>
                    singletonMap(Exception.class, true));
            FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
            fixedBackOffPolicy.setBackOffPeriod(100);
            retryTemplate.setRetryPolicy(policy);
            retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
            final RetryCallback<Object, Exception> retryCallback = new RetryCallback<Object, Exception>() {
                public Object doWithRetry(RetryContext context) throws Exception {
                    System.out.println("do some thing");
                    //设置context一些属性,给RecoveryCallback传递一些属性
                    context.setAttribute("key1", "value1");
                    System.out.println(context.getRetryCount());
                    throw new Exception("exception");
    //                return null;
                }
            };
    
            // 如果RetryCallback执行出现指定异常, 并且超过最大重试次数依旧出现指定异常的话,就执行RecoveryCallback动作
            final RecoveryCallback<Object> recoveryCallback = new RecoveryCallback<Object>() {
                public Object recover(RetryContext context) throws Exception {
                    System.out.println("do recory operation");
                    System.out.println(context.getAttribute("key1"));
                    return null;
                }
            };
    
            try {
                final Object execute = retryTemplate.execute(retryCallback, recoveryCallback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

参考资料

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Retry 是一个用于在失败情况下自动重试的库。它提供了一些注解和模板来简化重试逻辑的编写和配置。 要使用 Spring Retry,首先需要将其添加为项目的依赖项。在 Maven 项目中,可以通过在 pom.xml 文件中添加以下依赖项来实现: ``` <dependency> <groupId>org.springframework.retry</groupId> <artifactId>spring-retry</artifactId> <version>1.3.1</version> </dependency> ``` 然后,在需要进行重试的方法上添加 @Retryable 注解。该注解可以指定重试的次数、重试的异常类型以及可选的回退方法。例如: ```java import org.springframework.retry.annotation.Retryable; @Retryable(value = {CustomException.class}, maxAttempts = 3, backoff = @Backoff(delay = 1000)) public void retryMethod() throws CustomException { // 重试逻辑 } ``` 在上面的示例中,retryMethod() 方法将在捕获 CustomException 异常时进行最多三次重试。每次重试之间会等待 1000 毫秒。 最后,需要在 Spring 的配置类上添加 @EnableRetry 注解以启用重试功能。例如: ```java import org.springframework.context.annotation.Configuration; import org.springframework.retry.annotation.EnableRetry; @Configuration @EnableRetry public class AppConfig { // 配置类内容 } ``` 这样,Spring Retry 就会自动在发生异常时触发重试逻辑。 需要注意的是,Spring Retry 默认只会重试在方法内部抛出的异常,而不会重试外部异常(例如网络故障)。如果需要对外部异常进行重试,可以通过自定义 RetryPolicy 或使用 Spring 的 AspectJ 功能来实现。 希望这些信息能帮助到你使用 Spring Retry。如果有任何进一步的问题,请随时提问!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值