在Spring Boot中實(shí)現(xiàn)異步上傳文件可以通過使用@Async
注解實(shí)現(xiàn)。下面是一個(gè)簡(jiǎn)單的示例代碼:
@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) {
// 上傳文件的邏輯
// 這里可以調(diào)用其他Service或者使用Spring提供的ResourceLoader來保存文件
}
}
spring.task.execution.pool.core-size=5
spring.task.execution.pool.max-size=20
spring.task.execution.pool.queue-capacity=100
在上面的示例中,當(dāng)文件上傳請(qǐng)求到達(dá)時(shí),uploadFile
方法會(huì)被異步執(zhí)行,而不會(huì)阻塞主線程。這樣可以提高系統(tǒng)的并發(fā)處理能力。