When to use Spring @Async vs Callable controller (async controller, servlet 3)

谁说胖子不能爱 提交于 2019-11-26 22:48:00

问题


I would like to know the general use case of using @Async and Servlet 3 asynchronous request implementation in Spring using Callable.

As I understand, @Async is for making any method (specifically, any service method) execute asynchronously.

@Async
void doSomething(String s) {
// this will be executed asynchronously
}

and any controller which returns Callable

  @RequestMapping("/view")
public Callable<String> callableWithView(final Model model) {
    return new Callable<String>() {
        @Override
        public String call() throws Exception {
            Thread.sleep(2000);
            model.addAttribute("foo", "bar");
            model.addAttribute("fruit", "apple");
            return "views/html";
        }
    };
}

I am confused on whento use what. What will be the effect of using Asynchronous servlet/controller and with spring @Async together?


回答1:


This post has explanation for what you are looking for

Excerpt:

In some cases you can return to the client immediately while a background job completes processing. For example sending an email, kicking off a database job, and others represent fire-and-forget scenarios that can be handled with Spring's @Async support or by posting an event to a Spring Integration channel and then returning a confirmation id the client can use to query for the results.

Callable return type makes a controller method asynchronous. This is usually used in situations like long polling. Read this post by the same author for more information.

Also callable is an alternative for Runnable, in the sense, It can return results and throw checked exceptions.

Say you have a method

public String aMethod(){

}

This can be made asynchronous by simply returning a Callable interface.

public Callable<String>  aMethod(){

}



回答2:


you can not improve single request performance with using Callable interface, it helps to take more request in some cases. If your response type would be void, you can use runnable instead of callable, so with using runnable you can improve single request response time.



来源:https://stackoverflow.com/questions/17167020/when-to-use-spring-async-vs-callable-controller-async-controller-servlet-3

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