Can API Request (GET Call) return a response to client and start a background task to finish request

本秂侑毒 提交于 2019-12-11 14:26:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!