Specify timeout for controller async method in Spr

2020-03-24 07:11发布

问题:

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

回答1:

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.



回答2:

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



标签: spring-mvc