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

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

1 个月前提问
1 个月前修改
浏览次数12

1个答案

1

在Spring Boot应用程序中实现服务器发送事件(SSE,Server-Sent Events)是一种允许服务器主动向客户端推送信息的技术。SSE特别适合创建实时通知和更新的功能,如实时消息、股票行情更新等。下面我将通过一个简单的例子来展示如何在Spring Boot中实现SSE。

步骤 1: 创建Spring Boot项目

首先,需要创建一个Spring Boot项目。可以使用Spring Initializr(https://start.spring.io/)来快速生成项目结构。

步骤 2: 添加依赖

pom.xml中添加以下依赖或者如果使用Gradle, 则添加到build.gradle文件中:

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

步骤 3: 创建Controller

创建一个RestController,用来发送SSE。SSE的数据类型是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); // 每秒发送一次数据 emitter.send("SSE Msg " + i + " at " + System.currentTimeMillis()); } emitter.complete(); } catch (Exception ex) { emitter.completeWithError(ex); } }); return emitter; } }

步骤 4: 运行和测试

运行Spring Boot应用程序,并通过浏览器或者使用curl命令访问http://localhost:8080/stream-sse。你会看到服务器每秒发送一次消息,直到发送完10条消息。

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

以上是在Spring Boot中实现SSE的基本步骤和示例。你可以根据具体需求调整消息产生的逻辑,例如连接数据库实时获取变动数据等。在实际应用中,可能还需要处理连接异常、客户端断开连接等问题,确保系统的健壮性。

2024年8月7日 22:18 回复

你的答案