Use SseEmitter to implement streaming and data reception on the front-end of Spring Boot back-end
When building modern web applications, real-time data push is a very important requirement, such as AI dialogue streaming response, real-time notification push, etc. And in Spring Boot,SseEmitter
It is a very convenient tool that allows the backend to go to the frontendStreaming data transmission(Server-Sent Events, SSE for short). This article will describe how to use itSseEmitter
Create streaming and enable efficient interaction between the backend and the frontend.
1. What is SseEmitter?
SseEmitter
is a Spring Web forServer push event(SSE, Server-Sent Events) tool. It allows the server to continuously push data to the client without the need for the client to continuously poll.
Compared with WebSocket, SSE has the following advantages:
-
HTTP-based connections, no additional protocol support required, the front-end can be used directly
EventSource
Receive. - Support automatic reconnection, If the connection is disconnected, the browser will automatically try to re-establish the connection.
- More suitable for one-way push data scenarios, such as AI generates streaming text, server message push, etc.
2. Use SseEmitter in Spring Boot
2.1 Add dependencies
If your project is using Spring MVC, no additional dependencies are required. But if you are using Spring WebFlux, make sure yoursThe following dependencies are included (required only by WebFlux):
<dependency> <groupId></groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency>
2.2 Create a backend streaming interface
The java code example is as follows:
@RestController @RequestMapping("/api/chat") public class ChatController { @GetMapping("/stream") public SseEmitter streamResponse() { SseEmitter emitter = new SseEmitter(0L); // 0L means never timeout ().execute(() -> { try { for (int i = 1; i <= 5; i++) { ("information " + i); (1000); // Analog delay } (); } catch (Exception e) { (e); } }); return emitter; } }
3. How to receive streaming data on the front end
📌 Use fetch to process SSE (streaming data), fetch will not process streaming data by default, so we need to manually parse ReadableStream to receive data step by step.
✅ Front-end code (based on fetch/infetch)
async function fetchStreamData() { const response = await fetch("/api/chat/stream"); // Ensure that the server supports streaming data if (!) { throw new Error(`HTTP mistake!Status code: ${}`); } const reader = (); const decoder = new TextDecoder("utf-8"); // Read streaming data while (true) { const { done, value } = await (); if (done) break; // Decode and output data const text = (value, { stream: true }); ("Data received:", text); } ("Streaming Completed"); } // Call streaming requestfetchStreamData().catch();
📌 Why use fetch + ReadableStream?
- Better compatibility: The fetch API is a standard method for modern browsers and can handle more types of streaming data (such as JSON, HTML, binary) than EventSource.
- More flexible: can manually control data reading and support customized parsing methods.
- For AI big model return: if your backend is an AI interface like ChatGPT/DeepSeek API, fetch + stream is the best way.
This is the article about using SseEmitter to implement streaming of Spring Boot backend and data reception on the front-end. For more related Spring Boot SseEmitter streaming and data reception content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!