vue2+java Server-Sent Events (SSE)
时间: 2025-01-16 21:24:48 浏览: 67
### 实现 Server-Sent Events (SSE) 的 Vue2 和 Java 解决方案
#### 客户端:Vue2 中的 SSE 集成
为了在客户端集成 SSE,在 Vue 组件内可以创建一个新的 `EventSource` 对象来监听来自服务器的消息。
```javascript
export default {
name: 'SseComponent',
mounted() {
const eventSource = new EventSource('/api/sse-endpoint');
eventSource.onmessage = function(event) {
console.log('New message:', JSON.parse(event.data));
};
eventSource.onerror = function(error) {
console.error('Error occurred:', error);
};
this.$on('hook:beforeDestroy', () => {
eventSource.close();
});
}
}
```
上述代码展示了如何通过 `/api/sse-endpoint` URL 建立连接并处理接收到的数据[^1]。
#### 服务端:Java Spring Boot 下的 SSE 支持
对于基于 Java 的后端应用,Spring Framework 提供了对 SSE 的良好支持。下面是一个简单的控制器例子:
```java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SseController {
@GetMapping(value="/api/sse-endpoint", produces= MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamEvents() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> "data: Time is " + LocalDateTime.now());
}
}
```
这段程序会每秒发送一次时间戳给所有已订阅此事件流的客户端。
阅读全文
相关推荐


















