如何在Spring Boot中创建部分异步发布请求?

时间:2019-05-12 19:44:59

标签: java spring-boot http-post

我是Spring Boot的新手,我想创建一种异步请求。它应该允许用户上传文件。然后,Spring应用程序应将其保存并回答用户文件已正确保存。

然后整个异步部分发生。保存文件后,服​​务器应立即开始处理文件(在后台)。当前,它无法在后台运行(用户需要等待processFileInBackground完成):

控制器:

@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());
    }
}

1 个答案:

答案 0 :(得分:3)

Spring为您提供了 @Async 批注,您需要将异步逻辑分离到一个单独的类中,并使用此异步注释方法,这将在单独的线程中执行您的逻辑。 选中此https://spring.io/guides/gs/async-method/

请注意,您必须从调用方类的外部调用async方法才能在异步模式下执行

@CrossOrigin
@RestController
public class ProcessFileController {
    @Autowired
    ProcessFileService processFileService;

    @CrossOrigin
    @PostMapping("/files/upload")
    public ResponseEntity<String> singleFileUpload(@RequestParam("file") MultipartFile file) {
        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(){
       return fileProcessor.getResult();
    }

}

配置

@EnableAsync
@Configuration
public class AsyncConfig {
    @Bean(name = "threadPoolExecutor")
    public Executor getAsyncExecutor() {
      ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
      executor.setCorePoolSize(7);
      executor.setMaxPoolSize(42);
      executor.setQueueCapacity(11);
      executor.setThreadNamePrefix("threadPoolExecutor-");
      executor.initialize();
      return executor;
    }
}