springboot sse VUE3 消息推送
时间: 2025-02-07 13:57:02 浏览: 52
### 使用 Spring Boot 和 Vue3 实现 SSE 消息推送
#### 后端配置:Spring Boot 设置 SSE 控制器
为了实现实时消息推送,在 `Spring Boot` 中创建一个控制器来处理 SSE 请求。该控制器负责建立与客户端的连接并发送更新。
```java
package com.example.demo.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import java.time.Duration;
@RestController
@RequestMapping("/api/sse")
public class SseController {
@GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> streamEvents() {
// 创建无限流模拟持续的消息推送
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> "event-" + sequence);
}
}
```
此代码片段定义了一个 RESTful API 终结点 `/api/sse/events`,它返回一个无尽的数据流给订阅它的任何 HTTP 客户端[^1]。
#### 前端集成:Vue3 访问 SSE 接口
在前端部分,通过 JavaScript 的原生 `EventSource` 对象监听来自服务端的消息。下面是在 Vue3 单文件组件中的具体实现方式:
```html
<template>
<div id="app">
<h2>SSE Messages:</h2>
<ul v-if="messages.length > 0">
<li v-for="(msg, index) in messages" :key="index">{{ msg }}</li>
</ul>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const messages = ref([]);
let eventSource = null;
onMounted(() => {
const url = new URL('/api/sse/events', window.location.origin);
eventSource = new EventSource(url.toString());
eventSource.onmessage = function(event) {
console.log('New message:', event.data);
messages.value.push(event.data);
};
eventSource.onerror = () => {
console.error('Error occurred with the server-sent events');
eventSource.close();
};
});
onUnmounted(() => {
if (eventSource !== null && eventSource.readyState === 1) {
eventSource.close();
}
});
</script>
```
上述脚本展示了如何利用 Composition API 来管理生命周期钩子以及响应式状态。当页面加载完成之后会自动打开到指定路径下的 Server-Side Events 连接;每当收到新的事件通知就会将其追加至列表显示出来[^2]。
阅读全文
相关推荐


















