Server-Sent Events in Spring Boot

Mangesh More
Globant
Published in
4 min readAug 17, 2023
Photo by Taylor Vick on Unsplash

We all have used multiple applications to track live sports scores, investment strategies, and stock market updates with real-time notifications. Have you ever wondered about the technologies which are behind all these applications?

For receiving these real-time updates we have various technologies, such as WebSocket, Client Polling, and Server-Sent Events. In this article, we will learn primarily about the server-sent event and how we can integrate the same with the Spring Boot Application.

A Brief Overview of Server-Sent Events

Server-sent event is a technology used to establish a unidirectional channel between a server and a client to receive continuous updates from the server. Clients don’t need to poll the server for new updates like client polling continuously. A client needs to establish the initial HTTP connection with the server, and the server sends the data streams to the client via this connection. The server-sent event sends the events using a text/event-stream media type.

Server-Sent Events

Examples of how SSE can be used :

  • Real-Time Notification Systems: SSE can be used to implement real-time notification systems. For example, to provide an instant messaging experience, the application can use SSE to push new messages to the recipient’s browser.
  • Monitoring Systems: System admins could get real-time alerts and status updates for their servers, helping them to troubleshoot the issues quickly.
  • Live Event Streaming: SSE can provide real-time updates during live conferences, webinars, or seminars. Attendees can get real-time announcements, updated schedules, and other event-related content.

Server-sent event application with SseEmitter in Spring Boot

Spring Boot has SseEmitter a class available from version 4.2 to implement the server-sent event. Using SseEmitterwe will write a Spring Boot application that will send events to the client at a fixed interval of one second. The client system will be notified about every notification data server is emitting to it, and in that way, real-time modifications can be achieved at the client-side application.

Step 1: Set up a Spring Boot project :

Create a Spring Boot project and add all the necessary dependencies, including spring-boot-starter-web .

Step 2: Create an SSE endpoint

Create a new controller class and define an SSE endpoint to handle SSE requests.

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class SseEventController {
@GetMapping("/events")
public SseEmitter eventStream() {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
// Our SSE logic goes here
return emitter;
}
}

Step 3: Implement SSE logic

Inside the eventStream() method, we will add our logic to send the events to the client. We use SseEmitter to send the events to the client and SseEventBuilder create SseEvent.

import java.io.IOException;
import java.time.LocalTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class SseEventController {
@GetMapping("/events")
public SseEmitter eventStream() {
SseEmitter emitter = new SseEmitter();
ExecutorService sseMvcExecutor = Executors.newSingleThreadExecutor();
sseMvcExecutor.execute(() - > {
executeSseLogic(emitter);
});
return emitter;
}
private void executeSseLogic(SseEmitter emitter) {
try {
for (int counter = 0; counter < 10; counter++) {
// Create an event with a custom event ID and data
SseEmitter.SseEventBuilder event = SseEmitter.event().id(String.valueOf(counter))
.data("Event data at " + LocalTime.now());
// Send the event to the client
emitter.send(event);
// Wait for one second before sending the next event
Thread.sleep(1000);
}
// Mark the end of the event stream
emitter.complete();
} catch (IOException | InterruptedException e) {
emitter.completeWithError(e);
}
}
}

Step 4: Test the SSE endpoint

Server-sent event Endpoint Response

We can now run the spring boot application and access our Server-sent event endpoint at “http://localhost:8080/events” (as shown in the above screenshot). We are receiving the events at one-second intervals. Each event contains the event’s id and the data we have sent from our application. As SseEmitter supports different HTTP MediaType in event data, it is beneficial to send complex data in events. In this way, we have successfully created and tested our SSE endpoint.

Conclusion

In the above article, we understand how we get real-time notifications using Server-Sent Events and how to implement a server-sent event in a Spring Boot application using SseEmitter. Also, we can implement real-time notifications sending applications using WebSocketand Client Polling.

Further Reading

  • For more information about SseEmitter, check the official documentation page of SseEmitter here.
  • Read more about WebSocket here.

--

--