1.从流式接口中获取

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
fetch(
"",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({}) // params
}
).then((res) => {
const reader = res.body.getReader();
const decoder = new TextDecoder();

return reader.read().then(function processResult(result) {
// result { done, value }
console.log(result);
// end
if (result.done) {
// reader.cancel()
return;
}

const chunk = decoder.decode(result.value, {
stream: true
});

// do something
console.log(chunk);

return reader.read().then(processResult);
});
})
.catch(error => {
console.error('Error occurred while fetching event stream:', error);
});

2.后端Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@PostMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter eventStream(@RequestBody Object obj) {
SseEmitter emitter = new SseEmitter();
System.out.println(obj.toString());
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
executorService.scheduleAtFixedRate(() -> {
try {
// 模拟产生一条事件数据
String eventData = "Event data: " + System.currentTimeMillis();
emitter.send(SseEmitter.event().data(eventData));
} catch (IOException e) {
emitter.complete();
}
}, 0, 1, TimeUnit.SECONDS);
return emitter;
}

最后更新: 2023年11月07日 15:24