如何在Spring Boot中实现SSE(服务器发送事件)
在Spring Boot中实现SSE(Server-Sent Events),你需要创建一个REST控制器,使用SseEmitter
来发送事件。以下是一个简单的例子:
- 添加依赖(如果你使用的是Maven,则在pom.xml中添加):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 创建一个REST控制器:
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;
@RestController
public class SseController {
@GetMapping(path = "/stream-events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter handleSse() {
SseEmitter emitter = new SseEmitter();
// 在新线程中发送事件
new Thread(() -> {
try {
for (int i = 0; i < 5; i++) {
emitter.send("data:" + i + "\n\n"); // 发送事件
Thread.sleep(1000); // 每秒发送一次
}
emitter.complete(); // 完成事件流
} catch (Exception e) {
emitter.completeWithError(e); // 发送错误
}
}).start();
return emitter;
}
}
- 启动Spring Boot应用,并通过浏览器或其他客户端访问
/stream-events
端点以接收服务器发送的事件。
以上代码创建了一个REST端点/stream-events
,它使用SseEmitter
在连接打开时发送一系列事件。每个事件是一个简单的数字,通过HTTP连接连续推送给客户端。每个事件间隔1秒钟。当发送了5个事件后,调用emitter.complete()
结束事件流。
你可以根据实际需求修改事件内容和发送策略。
评论已关闭