@Retryable和@Recover的使用

	@Retryable和@Recover实现了重处理,重处理的场景是十分常见的,例如发起网络请求的时候,经常会因为网络波动等原因造成请求失败,产生异常,这时候可以使用@Retryable和@Recover简单的实现重处理。

 

添加maven依赖。

<dependency>
    <groupId>org.springframework.retry</groupId>
    <artifactId>spring-retry</artifactId>
</dependency>

贴上demo代码。

/**
 * @author hsw
 * @Date 17:29 2018/7/23
 */
@Slf4j
@EnableRetry
@Component
public class RecoryTest {

    public void test () {
        retry();
    }

    @Retryable(value = {RetryException.class},//指定发生的异常进行重试
            maxAttempts=3,                   //重试次数,默认即为3
            backoff = @Backoff(value = 2000))//每次重试延迟毫秒数
    public void retry () {
        log.info("retry start");
        throw new RetryException("retry fail");

    }

    @Recover
    public void recover (RetryException e) {
        log.info("recovery,{}",e.getMessage());

    }
}



/**
 * @author hsw
 * @Date 17:34 2018/7/23
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RecoryTestTest {

    @Autowired
    private RecoryTest recoryTest;

    @Test
    public void retry() {
        recoryTest.retry();
    }

    @Test
    public void test() {
        recoryTest.test();
    }
}
RecoryTest为demo实现类。
RecoryTestTest为测试类。

项目基于springboot,@EnableRetry注解可以添加在项目启动类上,也可以直接添加在具有@Retryable注解方法的类上。

通过在指定方法前添加@Retryable注解来实现重试。

@Retryable(value = {RetryException.class},//指定发生的异常进行重试
            maxAttempts=3,                   //重试次数,默认即为3
            backoff = @Backoff(value = 2000))//每次重试延迟毫秒数
    public void retry () {
        log.info("retry start");
        throw new RetryException("retry fail");

    }
 

被注解的方法发生异常时会重试 

@Retryable

  • value:指定发生的异常进行重试 
  • include:和value一样,默认空,当exclude也为空时,所有异常都重试 
  • exclude:指定异常不重试,默认空,当include也为空时,所有异常都重试 
  • maxAttemps:重试次数,默认3 
  • backoff:重试补偿机制,默认没有

@Backoff注解

  • delay:指定延迟后重试 
  • multiplier:指定延迟的倍数,比如delay=5000l,multiplier=2时,第一次重试为5秒后,第二次为10秒,第三次为20秒

@Recover 

当重试到达指定次数时,被注解的方法将被回调,可以在该方法中进行日志处理。需要注意的是发生的异常和入参类型一致时才会回调。

@Recover
    public void recover (RetryException e) {
        log.info("recovery,{}",e.getMessage());

    }

调用测试类的retry方法后执行结果如下:

调用test方法却无法得到预期结果,这是因为retry用到了aspect增强,在方法内部调用的时候,会使aspect增强失效,那么retry当然也会失效。

本文参考多篇博文,仅供学习记录使用。

猜你喜欢

转载自blog.csdn.net/qq_38439885/article/details/81174635