【问题标题】:Spring re-try withing future tasks not working未来任务中的春季重试不起作用
【发布时间】:2019-04-07 09:36:04
【问题描述】:

我有一个需要调用外部 API 的 spring-boot 应用程序。 如果有 'n' 个外部调用,将创建 'n' 个未来任务并进行剩余调用。这里的问题是,如果任何其他调用因异常而失败,我需要重试调用 3 次。 我尝试使用 Spring-retry,但它没有,失败时重试。

以下是到目前为止我尝试重试的代码 sn-p。 当任何被调用的服务关闭并且程序不会重试或进入恢复块时,我会立即收到 IO 异常。 是不是因为没有为新线程创建代理。

@SpringBootApplication
@EnableRetry
public class SpringBootWebApplication implements CommandLineRunner{

    @Autowired
    RestClient client;

    public static void main(String[] args) {
       SpringApplication.run(SpringBootWebApplication.class, args);
    }

      @Override
    public void run(String... args) throws Exception {

       String a[] = new String[] {args[0],args[1],args[2] }; 

            // getting the list view of Array 
            List<String> list = Arrays.asList(a); 

        client.executeRest(list)
    }

}

######

I have another class where future tasks will be created.

public class RestClient(){
     public void executeRest(List<String> uris)){

       ExecutorService executor = Executors.newFixedThreadPool(2);
       for(String uri : uris){
           Future<String> t = executor.execute(new MyCallable(uri));
        }
     }
}


public class MyCallable implements Callable<String> {

    private String endPoint;

    public MyCallable(String endPoint){
        this.endPoint=endPoint;
    }

    @Override
    public void call() throws Exception {     
         system.out.println(makeRestGetCall(String uri));
    }

     @Retryable(
      value = { Excelption.class }, 
      maxAttempts = 2,
      backoff = @Backoff(delay = 5000))
        public String makeRestGetCall(String uri){
           return restTemplate.exchange(uri, HttpMethod.GET,String.class);
        }

      @Recover
    void recover(Exception e){
      system.out.println("Max retries done")
     }

}

【问题讨论】:

  • 这是拼写错误Excelption.class

标签: spring spring-boot java-8 spring-retry futuretask


【解决方案1】:

只有当方法抛出一个值配置的异常时才会尝试重试(在你的情况下是Exception),restTemplate.exchange方法抛出多个Exceptions所以尝试使用自定义@ 987654323@

public class CustomException extends RuntimeException {

    }

重试方法

 @Retryable(
  value = { CustomException.class }, 
  maxAttempts = 2,
  backoff = @Backoff(delay = 5000))
    public String makeRestGetCall(String uri){
         try {
       return restTemplate.exchange(uri, HttpMethod.GET,String.class);
          }catch(Exception ex) {

           // do something or log something 
             throw new CustomException();
           }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    相关资源
    最近更新 更多