Server Sent Event Processing in Spring MVC 4.2, Spring MVC, Asynchronous

Author: Shazin Sadakath


In a previous post I spoke about the features Spring MVC 4.2 has from Streaming Request Processing. I have discussed how we can StreamingResponseBody to send large data asynchronously in a streaming manner. 

 

In this post I am planning to talk about SseEmitter which is another way to send semi structured data clients in an asynchronous streaming manner.

 

If you want to learn more about the definition and structure of a Server Sent Event you can read the Mozilla Documentation. But in short a Server Sent Event is a push event from a server which will be taking place inside of a single TCP/IP Socket connection from Client to Server. This event being push means it eliminates the need for constant polling of the Server for data thus reduces unwanted load on Server and the Client can receive the data in real time.

 

In Spring MVC following controller code can be written to send server sent events easily and in the client end Javascript can be used to read these events and present in the web page. For demo purpose I am showing a live Cricket match score and commentary coming down to a Web page client in real time. The server code will look like below; 

@RestController
@RequestMapping("/score")
public class ScoreController {

    private final String[] PLAYS = new String[]{"Driven through the covers, 4 runs",
            "Out! Bowled",
            "Lofted drive from 6",
            "Edged and 4",
            "Straight drive 2 runs",
            "Chip over covers, 1 run",
            "Good yorker, defended well"};

    private static ExecutorService executorService = Executors.newFixedThreadPool(10);

    @GetMapping
    public SseEmitter getScore() {
        final SseEmitter sseEmitter = new SseEmitter();
        executorService.submit(() -> {
            try {
                sseEmitter.send(" ------ New Over! ------");
                for (int i = 0; i < 6; i++) {
                    sseEmitter.send(String.format("%d : %s\n", i + 1, PLAYS[new Random().nextInt(6)]));
                    Thread.sleep(1000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                sseEmitter.complete();
            }
        });

        return sseEmitter;
    }
}

And Javascript client client code will look like below;
 


    
        Live Match Scores
    
    
        

Sri Lanka vs India Live Match Scores



 

And as you can see from the image below there is only one request being initiated to /score end point but multiple commentary data being received through that long lived connection.

 



Tags: ServerSentEvent SpringMVC
Views: 1142
Register for more exciting articles

Comments

Please login or register to post a comment.


There are currently no comments.