Spring MVC - HTTP Streaming using ResponseBodyEmitter

[Updated: Jan 3, 2017, Created: Jan 3, 2017]

A handler method which returns ResponseBodyEmitter can be used for HTTP Streaming.

ResponseBodyEmitter can send multiple Objects to the client, where each Object sent is written to the response with an HttpMessageConverter.


Let's see an example how to achieve that.

The controller

 @Controller
public class MyWebController {

  @RequestMapping("/")
  public ResponseBodyEmitter handleRequest () {

      final ResponseBodyEmitter emitter = new ResponseBodyEmitter();
      ExecutorService service = Executors.newSingleThreadExecutor();
      service.execute(() -> {
          for (int i = 0; i < 1000; i++) {
              try {
                  emitter.send(i + " - ", MediaType.TEXT_PLAIN);

                  Thread.sleep(10);
              } catch (Exception e) {
                  e.printStackTrace();
                  emitter.completeWithError(e);
                  return;
              }
          }
          emitter.complete();
      });

      return emitter;
  }
}


Spring boot main class

 @SpringBootApplication
public class HttpStreamingExample {
    public static void main (String[] args) {
        SpringApplication.run(HttpStreamingExample.class, args);
    }
}


Accessing in browser:




Wrapping ResponseBodyEmitter in ResponseEntity

The handler method can also return ResponseEntity with ResponseBodyEmitter wrapped as the body. We would probably want to do that to customize the status and headers of the response. Please look at our MyWebController3.java in the example project below.

Example Project


Dependencies and Technologies Used :
  • Spring Boot Web Starter 1.4.2.RELEASE: Starter for building web, including RESTful, applications using Spring MVC. Uses Tomcat as the default embedded container.
    Corresponding Spring version: 4.3.4.RELEASE
  • JDK 1.8
  • Maven 3.3.9

Http Streaming Examples Select All Download
  • spring-mvc-http-streaming
    • src
      • main
        • java
          • com
            • logicbig
              • example


See Also

Spring boot tutorials