SpringBoot / Vue 对SSE的基本使用(简单上手)
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
以下是一个简单的例子,展示如何在Spring Boot应用程序中使用SSE(Server-Sent Events),以及如何在Vue.js应用程序中接收和展示这些事件。
Spring Boot端:
- 创建一个SSE控制器:
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-sse", 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;
}
}
Vue.js端:
- 在Vue组件中,创建一个EventSource实例来监听来自Spring Boot应用程序的SSE:
<template>
<div>
<h1>SSE Events</h1>
<ul>
<li v-for="(event, index) in events" :key="index">{{ event.data }}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
events: [],
eventSource: null
};
},
created() {
this.eventSource = new EventSource('/stream-sse');
this.eventSource.onmessage = (event) => {
this.events.push(event);
};
this.eventSource.onerror = (error) => {
console.error(error);
};
},
beforeDestroy() {
this.eventSource.close();
}
};
</script>
在这个例子中,我们创建了一个简单的SSE服务端点,在Spring Boot应用程序中发送一个数字序列,然后在Vue.js应用程序中接收和显示这些事件。这个例子提供了一个基本的SSE实现,并且可以根据具体需求进行扩展和修改。
评论已关闭