【发布时间】:2019-05-12 19:44:58
【问题描述】:
我是 Spring Boot 新手,我想创建一种异步请求。它应该允许用户上传文件。然后 Spring 应用程序应该保存它并回答用户该文件已正确保存。
然后整个异步部分发生。服务器应在保存文件后立即开始处理文件(在后台)。目前,它不在后台运行(用户需要等到processFileInBackgroundfinishes):
控制器:
@CrossOrigin
@RestController
public class ProcessFileController {
@Autowired
ProcessFileService processFileService;
@CrossOrigin
@PostMapping("/files/upload")
public ResponseEntity<String> singleFileUpload(@RequestParam("file") MultipartFile file) {
System.out.println("singleFileUpload tid: " + Thread.currentThread().getId());
bytes = file.getBytes();
// Save file...
String plainText = new String(bytes, StandardCharsets.UTF_8);
processFileInBackground(plainText);
return new ResponseEntity<>("File successfully uploaded!", HttpStatus.OK);
}
private void processFileInBackground(String plainText) {
processFileService = new ProcessFileService(plainText);
String result = processFileService.getResult();
}
}
服务:
@Service
public class ProcessFileService {
private FileProcessor fileProcessor;
public CompilerApiService(String plainText){
fileProcessor = new FileProcessor(code);
}
@Async
public String getResult(){
System.out.println("getResult tid: " + Thread.currentThread().getId());
// The call below takes a long time to finish
return fileProcessor.getResult();
}
}
配置:
@EnableAsync
@Configuration
public class AsyncConfig {
@Bean
public Executor threadPoolTaskExecutor() {
return new ConcurrentTaskExecutor(Executors.newCachedThreadPool());
}
}
【问题讨论】:
-
您可以简单地创建一个线程来保存文件,然后您就可以开始处理了。
-
查看
@Async注释,例如here -
我的建议是尝试在此处发布代码以便我们解决问题
-
@Deadpool 我在使用 Async 注解后发布了一些代码,但我仍然面临一些问题...
标签: java spring-boot http-post