如何在Spring Boot应用中实现Server-Sent Events (SSE)功能,并解决浏览器不自动刷新的问题?
时间: 2025-06-09 18:59:21 浏览: 70
在Spring Boot应用中实现Server-Sent Events (SSE)通常涉及以下几个步骤:
1. 添加依赖:首先,在`pom.xml`文件中添加Spring WebFlux和相关的WebSocket支持依赖,例如:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
```
2. 创建SSE处理器:创建一个Controller或Handler类,使用`WebFluxServerResponseDecorator`装饰`Mono< Flux<DataEvent>>`来发送事件流。例如:
```java
@RestController
public class SSEController {
@GetMapping("/sse")
public Mono<Void> sse() {
return Flux.interval(Duration.ofSeconds(1))
.map(event -> new DataEvent("New message from server", LocalDateTime.now()))
.map(dataEvent -> ServerSentEvent.create(dataEvent.getTitle(), dataEvent.getMessage()));
}
}
private static class DataEvent {
private String title;
private String message;
// 构造函数、getter和setter...
}
```
3. 发布事件:这个Controller会定期发送新的`DataEvent`实例给客户端,每次间隔1秒。
4. 解决浏览器不自动刷新问题:由于SSE是基于HTTP长连接的,浏览器不会自动刷新连接。开发者需要在前端通过JavaScript监听数据事件,当接收到新数据时手动更新UI。常见的做法是在HTML页面上使用`EventSource`对象订阅服务器的事件流:
```javascript
const source = new EventSource('/sse');
source.addEventListener('message', function(e) {
console.log(e.data);
// 更新UI逻辑
});
```
5. 错误处理和断开连接:记得处理`onerror`事件并清理资源,如`source.close()`。
阅读全文
相关推荐
















