Spring Causes SseEmitter Cannot redirect after response has been posted
For a simple controller with this way:
@RequestMapping(method = RequestMethod.GET, value = "{id}/update")
public ResponseEntity<SseEmitter> update() throws IOException {
final SseEmitter sseEmitter = new SseEmitter();
return ResponseEntity.ok(sseEmitter);
}
I tried this too:
@RequestMapping(method = RequestMethod.GET, value = "{id}/update")
public SseEmitter update() throws IOException {
final SseEmitter sseEmitter = new SseEmitter();
return sseEmitter;
}
But both Tomcat 8.0.21 methods throw the above exception 30 seconds after the request is issued. What's going on under the hood?
+3
source to share
2 answers
This could be the default asynchronous timeout of your servlet container. You can change the default with Spring:
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
configurer.setDefaultTimeout(1000000);
}
}
+2
source to share
You can set a timeout for the SseEmitter in your constructor:
final SseEmitter sseEmitter = new SseEmitter(60000L); // Timeout in millis
The client will automatically connect, but by default it will wait 2-3 seconds. You can override this when sending messages:
// Instruct the client to reconnect after 500ms
emitter.send(SseEmitter.event().reconnectTime(500).data(message));
+2
source to share