在Spring Boot中实现异步上传文件可以通过使用@Async注解实现。下面是一个简单的示例代码:
@RestController public class FileUploadController { @Autowired private FileStorageService fileStorageService; @PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { fileStorageService.uploadFile(file); return ResponseEntity.ok("File uploaded successfully!"); } } @Service public class FileStorageService { @Async public void uploadFile(MultipartFile file) { // 上传文件的逻辑 // 这里可以调用其他Service或者使用Spring提供的ResourceLoader来保存文件 } } spring.task.execution.pool.core-size=5 spring.task.execution.pool.max-size=20 spring.task.execution.pool.queue-capacity=100 在上面的示例中,当文件上传请求到达时,uploadFile方法会被异步执行,而不会阻塞主线程。这样可以提高系统的并发处理能力。