简体   繁体   English

如何在Spring启动时创建部分异步发布请求?

[英]How to create partly async post request in Spring boot?

I'm new to Spring Boot and I would like to create a kind of async request. 我是Spring Boot的新手,我想创建一种异步请求。 It should allow user to upload a file. 它应该允许用户上传文件。 Then Spring application should save it and answer the user that the file was properly saved. 然后Spring应用程序应保存它并回答用户文件已正确保存。

Then the whole async part happens. 然后整个异步部分发生。 Server should start processing the file (in background) right after having it saved. 服务器应该在保存后立即开始处理文件(在后台)。 Currently, it does not run in background (user needs to wait until processFileInBackground finishes): 目前,它不在后台运行(用户需要等到processFileInBackground完成):

Controller: 控制器:

@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: 服务:

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

}

Configuration: 组态:

@EnableAsync
@Configuration
public class AsyncConfig {
    @Bean
    public Executor threadPoolTaskExecutor() {
        return new ConcurrentTaskExecutor(Executors.newCachedThreadPool());
    }
}

Spring offers @Async annotation to you, you need to separate your async logic in a separate class and annotate your method with this async, this will execute your logic in a separate thread. Spring为您提供@Async注释,您需要将异步逻辑分离到一个单独的类中并使用此异步注释您的方法,这将在一个单独的线程中执行您的逻辑。 Check this https://spring.io/guides/gs/async-method/ 检查这个https://spring.io/guides/gs/async-method/

Be ware that you must call the async method from outside the caller class in order to execute in async mode, something like this 必须要从调用者类外部调用异步方法才能在异步模式下执行,就像这样

@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 服务

@Service
public class ProcessFileService {

    private FileProcessor fileProcessor;

    public CompilerApiService(String plainText){
        fileProcessor = new FileProcessor(code);
    }

    @Async
    public String getResult(){
       return fileProcessor.getResult();
    }

}

Configuration 组态

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM