[英]How to stop webclient get() exchange() by calling executorService.shutdownNow()?
请告诉我如何解决这样的事情? 当我试图中断从 url 到 Spring WebFlux webClient 获取图像时 - 它不会停止。
我有下一个代码
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 时,“中断”标志会重置。 另一个问题是当块抛出异常时它抛出包裹的 InterruptedException
如果我尝试捕获并再次设置标志 InterruptedException 它不是 go 在条件内,就像
if (e instanceof InterruptedException){
Thread.currentThread().interrupt(); << this is never called
}
解决方案是:
if (Exceptions.unwrap(e) instanceof InterruptedException){
Thread.currentThread().interrupt(); << this is never called
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.