问题
I am using Spring Boot 1.4 and Java8. I want to know is it possible that if I receive a get request for an API in controller. I immediately return a response to the client and then create a background task for the request (that handle success and exception scenarios). I understand we can use completablefuture for async processing, but still from controller method for this API we generally send the response after using thenapply, exceptionally or get. That means though we have spawned a new thread. Main thread is still not free. I am looking for hit and forget kind of use case. Please suggest how it may be feasible.
回答1:
as stated in comments you can use async functionality from Spring. For that you'll need a configuration like
@EnableAsync
@Configuration
public class AsyncConfig {
@Bean
public Executor threadPoolTaskExecutor() {
return new ConcurrentTaskExecutor(Executors.newCachedThreadPool());
}
}
then put the annotation on the method which is running the background task
@Async
void runBgTask() { /* ... */ }
and call it in your controller method
@GetMapping("/foo")
public Foo hello() {
runBgTask();
return new Foo();
}
来源:https://stackoverflow.com/questions/56034828/can-api-request-get-call-return-a-response-to-client-and-start-a-background-ta