existSpring Boot, returntext/event-stream
Types of responses are usually used to implementServer-Sent Events (SSE), this method allows the server to push real-time updates to the browser. Client passEventSource
The API listens for and receives these events. Spring Boot can be used@RestController
andSseEmitter
To implement this function.
Step 1: Create SSE Controller and return text/event-stream
We can pass@GetMapping
To create an API, returntext/event-stream
Types of data. This data will be a continuous stream and the browser will receive it in real time.
Example: Return a response of type text/event-stream through Spring Boot
-
Controller: Define a return in Spring Boot
text/event-stream
Types of API interface. -
use
SseEmitter
:SseEmitter
is a class provided by Spring to handle Server-Sent Events streams. We can use it to push data to the client asynchronously.
Example 1: Simple SSE implementation
In this example, we will create a simple Spring Boot controller that will return a live stream of events (SSE).
import ; import ; import ; @RestController public class SseController { /** * This interface will return a continuous event stream, and the browser will receive it through EventSource */ @GetMapping("/sse") public SseEmitter handleSse() { SseEmitter emitter = new SseEmitter(); // Start a new thread to simulate periodic push events new Thread(() -> { try { for (int i = 0; i < 10; i++) { // Send data to the client ("data: Event " + i + "\n\n"); (1000); // Send once per second } (); // After sending, the mark event stream is completed } catch (Exception e) { (e); // If an exception occurs, the mark event leaks out } }).start(); return emitter; // Returns the SseEmitter instance, which handles asynchronous streaming data } }
illustrate:
-
SseEmitter
Used to handle SSE connections. We will pass the data()
Send to the client. - Event passed
data: <message>
Send format to the client, note that each message ends with two newline characters (\n\n
)。 -
(1000)
Used to simulate sending one event per second. If you need to send events regularly, it can be achieved through a similar mechanism. - Finally, by
()
Mark the end of the event stream. If an error occurs, use()
。
Step 2: Front-end receives SSE events
On the front end, use JavaScriptEventSource
API receives events pushed by the server. This API will maintain a connection to the server, and the browser will automatically handle it once new events are present.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Server-Sent Events Example</title> </head> <body> <h1>Server-Sent Events Example</h1> <div ></div> <script> // Create an EventSource object and connect to the /sse interface const eventSource = new EventSource("/sse"); // Process the event whenever data is received = function(event) { const messagesDiv = ('messages'); const message = ('p'); = ; (message); }; // Error handling = function(error) { ("EventSource failed:", error); }; </script> </body> </html>
Step 3: Configure Spring Boot to enable asynchronous support
SSE usually requires asynchronous processing, so it is important to enable asynchronous support in Spring Boot. Can be passed@EnableAsync
To enable asynchronous support.
Enable asynchronous support
import ; import ; @Configuration @EnableAsync public class AsyncConfig { }
Step 4: Timely push data (optional)
If you want to push events regularly (for example, push a message every certain time), you can use Spring's@Scheduled
Annotations to arrange timing tasks.
Example: Timed event sending
import ; import ; @Controller public class ScheduledSseController { private final SseEmitter emitter = new SseEmitter(); @Scheduled(fixedRate = 5000) // Send an event every 5 seconds public void sendScheduledEvent() { try { ("data: Scheduled Event at " + () + "\n\n"); } catch (IOException e) { (e); } } }
In the example above,@Scheduled(fixedRate = 5000)
Events will be sent regularly every 5 seconds.
Step 5: Handle multi-client connections
If you need to manage multiple client connections, you canSseEmitter
The instance is stored in a list and events are sent for each connection. Whenever there is a new event, you can send events to all connected clients by traversing these connections.
import ; import ; import ; import ; import ; import ; @Controller public class MultiClientSseController { private final List<SseEmitter> emitters = new CopyOnWriteArrayList<>(); @GetMapping("/sse") public SseEmitter handleSse() { SseEmitter emitter = new SseEmitter(); (emitter); // Send data in a new thread new Thread(() -> { try { for (int i = 0; i < 10; i++) { for (SseEmitter e : emitters) { ("data: Event " + i + "\n\n"); } (1000); // Send once per second } } catch (Exception e) { (SseEmitter::completeWithError); } }).start(); return emitter; } }
Summarize
-
return
text/event-stream
: Used in Spring Boot ControllerSseEmitter
Or directly pass@GetMapping
Return streaming data. -
Front-end reception event: Using the browser
EventSource
API to receive event streams. -
Timed events: Can be used
@Scheduled
To push events regularly, or push dynamic data through background threads. -
Multi-client support: Can manage multiple
SseEmitter
instance, push events for each client.
This method is very suitable for real-time data push, such as stock market updates, social media notifications, real-time messages and other application scenarios.
This is the article about Springboot implementation of Server-Sent Events project practice. For more related Springboot implementation of Server-Sent Events, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!