0%

Spring对Server-Sent-Events的支持

SSE

SseEmitter (a subclass of ResponseBodyEmitter) provides support for Server-Sent Events, where events sent from the
server are formatted according to the W3C SSE specification. To produce an SSE stream from a controller, return
SseEmitter, as the following example shows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@GetMapping(path="/events", produces=MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter handle() {
SseEmitter emitter = new SseEmitter();
// Save the emitter somewhere..
return emitter;
}

// In some other thread
emitter.send("Hello once");

// and again later on
emitter.send("Hello again");

// and done at some point
emitter.complete();

While SSE is the main option for streaming into browsers, note that Internet Explorer does not support Server-Sent
Events. Consider using Spring’s WebSocket messaging with SockJS fallback transports (including SSE) that target a wide
range of browsers.

前端支持

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>fetch-sse</title>
<script src="js/vue3.2.13/dist/vue.global.js"></script>
</head>
<body>
<div id="sse-rendering">
<p>Accept:{{message}}</p>
<button v-on:click="fetchData">开始</button>
<button v-on:click="closeFetch">结束</button>
</div>
</body>
<script>
const SseRendering = {
data() {
return {
message: null,
eventSource: null
}
},
methods: {
fetchData() {
console.log(window)
let sse = this
this.eventSource = new EventSource("http://localhost:8080/test-sse");
this.eventSource.onmessage = function (e) {
sse.message = e.data
console.log(this)
console.log(e.data)
}
},
closeFetch() {
if (this.eventSource != null) {
this.eventSource.close()
}
}
}
}
Vue.createApp(SseRendering).mount("#sse-rendering")
</script>
</html>

Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.

Quick Start

Create a new post

1
$ hexo new "My New Post"

More info: Writing

Run server

1
$ hexo server

More info: Server

Generate static files

1
$ hexo generate

More info: Generating

Deploy to remote sites

1
$ hexo deploy

More info: Deployment

什么是Hexo?

Hexo 是一个快速、简洁且高效的博客框架。

环境要求

  1. Node.js(Node.js 12.0 及以上版本)
  2. Git

安装步骤

script
1
2
3
4
5
6
7
8
#全局安装hexo
npm install -g hexo

#项目初始化
hexo init

#本地运行
hexo s