You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring中实现SSE实时推送时数据仅在连接关闭时发送的问题咨询

Spring中实现SSE实时推送时数据仅在连接关闭时发送的问题咨询

各位大佬好,我最近在做Spring的SSE实时推送功能,需求是每秒向前端推送一次服务器时间,但遇到了一个奇怪的问题:所有的ServerSentEvent都是在连接关闭的时候才一次性发送给前端,而不是每秒钟实时推送。

最开始我用Flux实现了这段代码:

@GetMapping("/flux", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
@ResponseBody
fun flux(): Flux<ServerSentEvent<String>> {
    return Flux.interval(Duration.ofSeconds(1L)).map { sequence ->
        ServerSentEvent.builder<String>()
            .id(sequence.toString())
            .event("heartbeat")
            .data("SSE - " + Instant.now().epochSecond.toString())
            .build()
    }
}

前端我用的是EventSource来接收:

const eventSource = new EventSource('/dashboard/updates');
eventSource.onmessage = (msg) => console.log(msg);

但运行后发现,只有当我关闭连接时,所有攒下来的SSE消息才会一下子被前端接收到,完全不是预期的每秒一条。

之后我又尝试不用Flux,改用SseEmitter配合定时任务的方式:

@GetMapping("/updates", produces = [MediaType.TEXT_EVENT_STREAM_VALUE])
@PreAuthorize("hasAuthority('ADS')")
@ResponseBody
fun updates(): SseEmitter {
    val emitter = SseEmitter()
    emitters.add(emitter)
    return emitter
}

@Scheduled(fixedDelay = 5000)
protected fun ping() {
    emitters.forEach { emitter ->
        try {
            emitter.send("Something")
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}

结果还是一样的问题,消息还是要等连接关闭才会批量发送,有没有大佬能帮我看看哪里出问题了?怎么才能让SSE消息实时推送给前端呢?

备注:内容来源于stack exchange,提问作者Georglider

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:44:30