如何通过调用executorService.shutdownNow来停止webclient getexchange?

问题描述

请告诉我我该如何解决? 当我尝试中断通过Spring WebFlux webClient从url获取图像时-它不会停止。

我有下一个代码

method1(){
...
ExecutorService executor = Executors.newFixedThreadPool(3);

for (String url: urlList){
  executor.submit(
    () -> {

      //byte[] byteImage = getImage(url)

      //save in file system (byteImage)

      //save in DB (byteImage)

      //save in redis (byteImage)
    }
)}
...
}

  public byte[] getImage(String url) {


    byte[] result = null;

    try {
      webClient
          .get()
          .uri(url)
          .header("X-Requested-With","XMLHttpRequest")
          .exchange()
          .flatMap(response -> {
            if (!response.statusCode().is2xxSuccessful()) {
              return Mono.error(new RuntimeException("Internal server error"));
            } else {
              return response.bodyToMono(ByteArrayResource.class);
            }
          }).map(ByteArrayResource::getByteArray)
          .block();
    } catch (Exception e) {
        log.warn("can't take screenshot {}",url);
    }

    return result;
  }

在另一个线程中,我尝试通过以下方式中断所有执行程序线程 executor.shutdownNow()

如果我删除webClient #block()-一切正常。 所有线程成功中断,该过程停止。

但是,如果webClient具有block()方法,则执行程序无法停止执行。

请帮助,如何解决此问题?

解决方法

我找到了解决方案。 问题是,当我捕获InterruptedException时,标志“ interrupted”将重置。另一个问题是,当块引发异常时,它会引发包裹的InterruptedException

如果我尝试捕获并再次设置标志InterruptedException,则它不在条件之内,例如

if (e instanceof InterruptedException){
  Thread.currentThread().interrupt(); << this is never called
}

解决方案是:

if (Exceptions.unwrap(e) instanceof InterruptedException){
  Thread.currentThread().interrupt(); << this is never called
}

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...