我想在Spring Boot应用程序中为匹配的请求映射子集配置异步处理支持/async/*
。例子:
localhost:8080/async/downloadLargeFile
localhost:8080/async/longRunningRask
以第一个示例为例,我使用StreamingResponseBody
以下方法实现了我的方法:
@GetMapping
public ResponseEntity<StreamingResponseBody> downloadLargeFile() throws IOException {
long size = Files.size(path);
InputStream inputStream = Files.newInputStream(path);
return ResponseEntity.ok()
.contentLength(size)
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=large_file.txt")
.body(inputStream::transferTo);
}
在的文档中StreamingResponseBody
,它指出我应该配置AsyncTaskExecutor
,因此我也实现了这个@Configuration类WebMvcConfigurer
:
@Configuration
public class AsyncConfigurer implements WebMvcConfigurer {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(-1);
configurer.setTaskExecutor(asyncTaskExecutor());
}
@Bean
public AsyncTaskExecutor asyncTaskExecutor() {
return new SimpleAsyncTaskExecutor("async");
}
}
但是,我无法找到一种仅对符合给定模式的请求使用此任务执行程序的方法。
作为一个更普遍的问题- 我如何将限制WebMvcConfigurer
为仅适用于与模式匹配的请求子集?
如果不可能或不建议这样做,则完成相同行为的正确方法是什么?
该TaskExecutor
配置用于当/与WebMvcConfigurer
在AsyncSupportConfigurer
将完全被用于Web请求的异步处理。所有其他请求均由servlet容器上可用的默认请求处理线程处理。
异步性质由方法的返回类型定义。Spring参考指南的MVC异步部分中介绍了异步类型。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句