Server-sent events (SSE) are standards that define how servers can start sending data to clients. Once an initial client connection has been established, in the context of Spring WebFlux, SSE allows you to send a stream of updates from the server to the client over HTTP.

SSE works over a single HTTP connection where the server continuously sends data to the client. Whenever there's new data available on the server, it sends an event to the client. The client receives these events and can react to them accordingly. The client establishes an HTTP connection to the server, and the server keeps the connection open indefinitely.

Key Features of SSE:

  • Text-Based: SSE sends data as text usually in UTF-8 making it easy to consume with JavaScript.
  • Event Stream Format: SSE uses a simple text-based format where each event is represented by a set of fields like data, events, ID, and others.
  • Automatic Re-connection: If the connection is closed, the client automatically tries to reconnect after a certain interval.
  • Built-in Retry Mechanism: SSE includes a built-in mechanism for handling re-connection attempts with an optional retry timeout.
SSE in Spring WebFlux

Prerequisites:

  • Spring Framework
  • Spring WebFlux
  • Publisher and Consumer in Spring WebFlux
  • RESTful APIs and It's Workflow
  • HTTP Status codes
  • Spring Stater project creation

Tools & Technologies:

  • Spring Boot version: 2.6.5
  • Spring Reactive programming
  • Spring Tool Suite
  • Project Type: Maven

Spring Project Dependencies:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

Steps to Implement Server-Sent Events (SSE) in Spring WebFlux

Here, we created one simple spring reactive project after that we created one controller class for defining the business logic and defining API endpoints. Below, we provide a in detail explanation with examples for a better understanding of the concept.

Step 1: Create a Spring Starter Project

Create a Spring Stater project with required dependencies. In the above, we provide those dependencies that we use in that spring project. Below, we provide the project folder structure.

Project Structure:

Project Folder Structure

Step 2: Create a Controller Class

Now create one class with the help of @ RestConfiguration annotation. This class can handle the business logic-related functions in the Application. And also define the API endpoints in this class.

SSEController.java:

package com.app;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
import java.time.LocalDateTime;
@RestController
public class SSEController {
    @GetMapping("/events")
    public Flux<ServerSentEvent<String>> getEvents() {
        return Flux.interval(Duration.ofSeconds(1))
                .map(sequence -> ServerSentEvent.<String>builder()
                        .id(String.valueOf(sequence))
                        .event("message")
                        .data("Event #" + sequence + " at " + LocalDateTime.now())
                        .build());
  • In the above java class, first we created a API endpoint by using @GetMapping.
  • After that we define a API endpoint method with the help of Flux publisher.
  • And, in this getEvents method we return the a flux of events.
  • These events contains information like event is, message, date and time of event.


Step 3: Run the Project

Once development is completed, then run this project as Spring Boot App and by default this Spring WebFlux project running Netty server on port number 8080.

Step 4: Test the API

Now test the API endpoint. Here, we use the Postman tool for API testing.

http://localhost:8080/events

Output:

API Testing

In Browser, we got output like below:

Similar Reads

Enable Swagger in Spring WebFlux
Spring Reactive programming is an asynchronous and non-blocking program paradigm for developing highly responsive applications. And also It enables developers to build applications to handle high-load traffic without compromising on application performance. Swagger is an open-source framework with a
5 min read
Reactive JWT Authentication Using Spring WebFlux
JSON Web Token (JWT) authentication is a popular method for securing APIs in microservices architectures. With Spring WebFlux, the reactive web framework, we can create highly scalable and responsive applications. In this article, we will guide you on how to implement JWT authentication in a reactiv
8 min read
Spring Webflux Vs Rsocket
Spring WebFlux and RSocket are tools offered by the Spring ecosystem for developing reactive applications. Their functions and features are different. Spring Webflux, Reactive stream semantics for non-blocking activities may be implemented in a web application. RSocket, reactive Stream semantics bet
5 min read
Rate Limiting in Spring WebFlux
Rate limiting is a crucial technique to control the amount of incoming traffic to the server. This prevents abuse, ensures fair resource usage, and protects against potential Denial of Service (DOS) attacks. In the Spring WebFlux, rate limiting can be implemented effectively using the Spring Cloud G
5 min read
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy Cookies are not collected in the GeeksforGeeks mobile applications. Got It !