问题描述
我正在使用Spring Boot 1.4和Java8.我想知道是否有可能在控制器中收到对API的获取请求.我立即将响应返回给客户端,然后为请求创建后台任务(处理成功和异常情况).我知道我们可以使用completablefuture进行异步处理,但是仍然从该API的控制器方法中,我们通常在使用thenapply,exclusive或get之后发送响应.这意味着尽管我们产生了一个新线程.主线程仍然不是空闲的.我正在寻找一劳永逸的用例.请提出可行的建议.
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.
推荐答案
您可以使用Spring的异步功能.为此,您需要一个类似
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();
}
这篇关于API请求(GET调用)是否可以将响应返回给客户端并启动后台任务以完成请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!