乐闻世界logo
搜索文章和话题

How can you implement server-sent events ( SSE ) in a Spring Boot application?

1个答案

1

In Spring Boot applications, implementing Server-Sent Events (SSE) is a technique that allows the server to actively push information to the client. SSE is particularly well-suited for creating real-time notifications and updates, such as real-time messaging and stock market updates. Below, I'll demonstrate how to implement SSE in Spring Boot with a simple example.

Step 1: Create a Spring Boot Project

First, create a Spring Boot project. You can use Spring Initializr (https://start.spring.io/) to quickly generate the project structure.

Step 2: Add Dependencies

Add the following dependencies to your pom.xml or build.gradle file:

xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

Step 3: Create Controller

Create a RestController for sending SSE. The data type for SSE is text/event-stream.

java
import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @RestController public class SseController { private final ExecutorService executorService = Executors.newCachedThreadPool(); @GetMapping(path = "/stream-sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter streamSse() { SseEmitter emitter = new SseEmitter(); executorService.execute(() -> { try { for (int i = 0; i < 10; i++) { Thread.sleep(1000); // Send data every second emitter.send("SSE Msg " + i + " at " + System.currentTimeMillis()); } emitter.complete(); } catch (Exception ex) { emitter.completeWithError(ex); } }); return emitter; } }

Step 4: Run and Test

Run the Spring Boot application and access http://localhost:8080/stream-sse using a browser or the curl command. You'll see the server sending messages every second until all 10 messages are sent.

bash
curl http://localhost:8080/stream-sse

The above are the basic steps and example for implementing SSE in Spring Boot. You can adjust the message generation logic according to your specific requirements, such as fetching real-time data from a database. In actual applications, you may also need to handle connection exceptions and client disconnections to ensure system robustness.

2024年8月7日 22:18 回复

你的答案