springboot retry

 try/catch,while 循环或者定时任务  这样看起来 好  low

sping boot  retry , 这样代码更简洁

eg:方式一:

    
    @Retryable(value= {RemoteAccessException.class},maxAttempts = 3,backoff = @Backoff(delay = 5000l,multiplier = 1))
    public void hahha() throws Exception {
            System.err.println("************************");
            System.out.println("do something...");
            throw new RemoteAccessException("调用异常");
    }
    
    
    
    @Recover
    public void recover(RemoteAccessException e) {
            System.out.println(e.getMessage());
    }
    

 eg:方式二 , 说明 1.上面的参数,在recover,可以拿到,需要那那个参数,写进去就可以了

        2. 如果有返回值,那么返回值的类型必须一样,下例中,都是void

 
    
    @Retryable(value= {RemoteAccessException.class},maxAttempts = 3,backoff = @Backoff(delay = 5000l,multiplier = 1))
    public void hahha(String name ,String addr) throws Exception {
            System.err.println("************************");
            System.out.println("do something...");
            addr="AAAAA";
            throw new RemoteAccessException("调用异常");
    }
    
    
    
    @Recover
    public void recover(RemoteAccessException e,String addr,String name) {
            System.out.println(e.getMessage());
            
            System.out.println("name :"+name);
            System.out.println("addr :"+addr);
    }

使用:

1.依赖:

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

<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>

2. 应用启动类开启 retry

@EnableRetry
public class Application {
    .......
}

3. 在指定方法上标记 @Retryable 来开启重试


@Retryable(value={A异常.class,B异常.class},
     maxAttempts=重试次数,
     backoff = @Backoff(delay = 延迟毫秒数,multiplier = 延迟倍数))
public void retryTest() throws Exception {
    System.out.println(Thread.currentThread().getName()+" do something...");
    throw new RemoteAccessException("RemoteAccessException....");
}

4. 在指定方法上标记 @Recover 来开启重试失败后调用的方法 (注意, 需跟重处理方法在同一个类中)

  @Recover
  public void recover(A异常 e) {
    // ... do something
  }

  @Recover
  public void recover(B异常 e) {
    // ... do something
  }

使用详解

spring-retry 通过 AOP 实现对目的方法的封装,执行在当前线程下,所以重试过程中当前线程会堵塞。如果 BackOff 时间设置比较长,最好起异步线程重试(也可以加 @Async 注解)。

@Retryable 注解

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

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

@Backoff 注解

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

@Recover

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

本文参考 
http://blog.csdn.net/u014513883/article/details/52371198

原文地址:https://www.cnblogs.com/lshan/p/10576735.html