Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify timeout for controller async method in Spring

Tags:

spring-mvc

I have a Spring MVC app backed by Java config and I would like to set up a default timeout for all async calls that involve Callable<> interface. For instance, consider controller method like this:

@RequestMapping
public Callable<String> doSmth() {
    return () -> {
        return "myview";
    }
}

I would like to have a controler (per application) of how much time controller has time to do its stuff before the request times out.

I would like to have an example of Java config, not xml

like image 320
Sergei Ledvanov Avatar asked Dec 17 '15 15:12

Sergei Ledvanov


People also ask

What is Spring MVC async request timeout?

With async method one can use spring. mvc. async. request-timeout= to set amount of time (in milliseconds) before asynchronous request handling times out. However, using Async Servlet with Spring MVC requires changing the controller methods return types.

How do you implement timeout in REST API?

One way we can implement a request timeout on database calls is to take advantage of Spring's @Transactional annotation. It has a timeout property that we can set. The default value for this property is -1, which is equivalent to not having any timeout at all.


2 Answers

You can do it by extending WebMvcConfigurerAdapter and overriding configureAsyncSupport:

 @Configuration
//other annotations if needed
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(100000); //in milliseconds
        super.configureAsyncSupport(configurer);
    }

or directly on the RequestMappingHandlerAdapter.

like image 96
jny Avatar answered Oct 29 '22 07:10

jny


You can also override the default timeout of 10 secs by setting the "asyncTimeout" attribute in Tomcat's conf/server.xml configuration file:

<Connector connectionTimeout="20000" asyncTimeout="30000" maxThreads="1000"
    port="8080" protocol="org.apache.coyote.http11.Http11NioProtocol"
    redirectPort="8443" />

Reference: https://tomcat.apache.org/tomcat-7.0-doc/config/http.html

like image 1
Manish Baruah Avatar answered Oct 29 '22 08:10

Manish Baruah