In modern web application development, real-time data push has become the core requirement of many business scenarios, such as real-time notifications, stock price updates or online chats. Traditional polling methods are inefficient, while SSE (Server-Sent Events) is a lightweight technology provided by HTML5, which can realize real-time data push from server to client through a one-way long connection. Spring Boot 3.4.3 combines Spring WebFlux to provide developers with responsive programming capabilities, making SSE functions simpler and more efficient. This article will introduce in detail how to implement SSE functions based on Spring WebFlux in Spring Boot 3.4.3, and provide complete code examples to help you quickly implement real-time push requirements in enterprise-level applications.
1. Introduction to SSE
1.1 What is SSE?
SSE (Server-Sent Events) is a server push technology based on the HTTP protocol, allowing the server to actively send data to the client. The client establishes a long connection to receive event streams pushed by the server, which are suitable for scenarios that require real-time updates. Compared to WebSocket, SSE is one-way communication (server to client only), which is simpler to implement and native browser support.
1.2 Advantages of SSE
- Lightweight: Based on HTTP, no additional protocol support is required.
- Simplicity: Low implementation cost, suitable for one-way push scenarios.
- Automatic reconnection: After the client is disconnected, it can automatically try to reconnect.
- compatibility: HTML5 standard, supported by mainstream browsers.
1.3 Applicable scenarios
- Real-time notifications (such as message reminders).
- Data monitoring (such as server status update).
- One-way event stream (such as log push).
2. Introduction to Spring WebFlux
Spring WebFlux is a responsive web framework introduced by Spring 5. Unlike traditional Spring MVC, it is based on the Reactor project and supports an asynchronous non-blocking programming model. Spring Boot 3.4.3 integrates Spring WebFlux by default, allowing developers to easily build highly concurrent, event-driven applications. Combined with SSE, WebFluxFlux
Data flow is ideal for handling real-time push requirements.
3. Project practical combat
The following are the complete steps to implement SSE functionality based on Spring Boot 3.4.3 and Spring WebFlux.
3.1 Adding Maven dependencies
existAdd Spring WebFlux dependencies:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="/POM/4.0.0" xmlns:xsi="http:///2001/XMLSchema-instance" xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0."> <modelVersion>4.0.0</modelVersion> <parent> <groupId></groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.4.3</version> </parent> <artifactId>springboot-sse</artifactId> <properties> <>17</> <>17</> <>UTF-8</> </properties> <dependencies> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> </dependencies> </project>
illustrate:
-
spring-boot-starter-webflux
Provides the core functionality of WebFlux and Reactor dependencies. - Spring Boot 3.4.3 uses JDK 17 to ensure the compiler version matches.
3.2 Creating an SSE controller
Create a controller that pushes event streams:
package ; import ; import ; import ; import ; import ; import ; import ; /** */ @RestController public class SSEController { // Define a counter to simulate data changes private final AtomicInteger counter = new AtomicInteger(0); @GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<Integer>> streamEvents() { return ((1)) .map(seq -> ServerSentEvent.<Integer>builder() .id((seq)) .event("message") .data(()) .build()); } }
Code description:
-
@GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
: Specifies to return the SSE event stream. -
((1))
: Generate an event per second. -
()
: Constructs SSE events, includingid
(Event ID),event
(Event Type) anddata
(Push data).
3.3 Front-end page example
Create a simple HTML page to receive SSE data:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>SSE Demo</title> </head> <body> <h1>SSE Data push</h1> <div ></div> <script> const eventSource = new EventSource("http://localhost:8080/sse"); = function(event) { ("result").innerText += "Data received: " + + "\n"; }; = function() { ("SSE connection failed"); (); }; </script> </body> </html>
Save as, placed in
src/main/resources/static
In the directory.
3.4 Start and Test
- Launch the Spring Boot app.
- Access in a browser
http://localhost:8080/
, you will see the page updated counter data every second. - Or access directly
http://localhost:8080/sse
, view the original event stream:
id: 0 event: message data: 1 id: 1 event: message data: 2
4. Advanced functions (optional)
Custom event type
Modify the controller to support multiple events:
@GetMapping(path = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<ServerSentEvent<String>> streamEvents() { return ((1)) .map(seq -> ServerSentEvent.<String>builder() .id((seq)) .event(seq % 2 == 0 ? "even" : "odd") .data("Count: " + ()) .build()); }
Dynamically push specific users
Use Map to store user connections:
private final Map<String, <String>> userSinks = new ConcurrentHashMap<>(); @GetMapping("/sse/{userId}") public Flux<ServerSentEvent<String>> userStream(@PathVariable String userId) { <String> sink = (userId, k -> ().multicast().onBackpressureBuffer()); return ().map(data -> ().data(data).build()); }
Exception handling
Add error reconnect logic:
return ((1)) .map(seq -> ServerSentEvent.<Integer>builder().data(()).build()) .onErrorResume(e -> (().data("Error: " + ()).build()));
5. Summary
Spring Boot 3.4.3 combines Spring WebFlux to implement SSE functions, providing an elegant solution for real-time data push. Through the steps in this article, you can quickly build an event-driven back-end service to meet the needs of real-time notification or monitoring. Compared with WebSocket, SSE is lighter and easy to integrate, suitable for one-way push scenarios.
This is the end of this article about Spring Boot 3.4.3, implementing SSE functions based on Spring WebFlux. This is the end of this article. For more related Spring Boot Spring WebFlux SSE content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!