Spring Boot REST API - request timeout?
I would suggest you have a look at the Spring Cloud Netflix Hystrix starter to handle potentially unreliable/slow remote calls. It implements the Circuit Breaker pattern, that is intended for precisely this sorta thing.
See offcial docs for more information.
You need to return a Callable<>
if you want spring.mvc.async.request-timeout=5000
to work.
@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(8000); //this will cause a timeout
return "foobar";
}
};
}
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
A fresh answer for Spring Boot 2.2 is required as server.connection-timeout=5000
is deprecated. Each server behaves differently, so server specific properties are recommended instead.
SpringBoot embeds Tomcat by default, if you haven't reconfigured it with Jetty or something else. Use server specific application properties like server.tomcat.connection-timeout
or server.jetty.idle-timeout
.
As commented by Wilkinson:
Setting the connection timeout will only result in a timeout when the client connects but is then too slow to send its request. If you want the client to wait for a maximum of 30 seconds for a response you will have to configure that on the client-side. If you want the server-side to only spend a maximum of 30 seconds handling the request there is no way to guarantee that as you cannot force the thread that is handling the request to stop.
You can also try setting spring.mvc.async.request-timeout