spring boot rest 接口实现流式响应,核心在于将 controller 方法的返回值类型声明为 sseemitter、responseentity 或 flux,并立即返回该对象实例。这样做能让 servlet 容器保持连接打开,允许服务端在后续逻辑中持续向客户端推送数据,直到连接关闭或超时。具体做法是配置好超时时间以防连接挂起,并在业务逻辑完成后调用相应的完成方法以释放资源。

SseEmitter 如何管理长连接的生命周期
SseEmitter 通过内部维护一个待发送队列和状态机来管理连接,它会在创建时启动一个异步线程处理发送任务,并在超时或异常时触发回调清理资源。

import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
public class SseController {
public SseEmitter streamData() {
// 设置超时时间为 60 秒,避免连接永久挂起
SseEmitter emitter = new SseEmitter(60000L);
// 注册完成回调,确保连接断开时清理资源
emitter.onCompletion(() -> System.out.println("SSE connection completed"));
emitter.onTimeout(() -> System.out.println("SSE connection timed out"));
// 模拟异步生成数据并推送
new Thread(() -> {
try {
for (int i = 0; i <p>上述代码展示了 <code>SseEmitter</code> 的标准用法。创建实例时必须指定超时时间,否则默认值为 -1(无限期),这可能导致服务器资源耗尽。发送数据时使用 <code>send()</code> 方法,该方法是非阻塞的,如果队列满或连接已关闭会抛出 <code>IOException</code>。最后必须调用 <code>complete()</code> 或 <code>completeWithError()</code> 来通知客户端连接结束,否则客户端可能一直等待。</p><h2>
<code>StreamingResponseBody</code> 与 <code>SseEmitter</code> 的区别是什么</h2><p><code>StreamingResponseBody</code> 基于 Servlet 3.0 的异步输出流,它直接在 Tomcat 等容器的 IO 线程上执行写入操作,适合简单的字节流传输,而 <code>SseEmitter</code> 提供了更高级的事件封装和超时控制机制。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer"><img
src="https://img.php.cn/upload/skill/000/000/081/179103250068943.jpg" alt="Spring Boot Actuator Analyzer" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer" class="overflowclass">Spring Boot Actuator Analyzer</a>
<p class="overflowclass">分析Spring Boot Actuator端点的安全性、健康检查、指标暴露及生产配置——审计信息、健康状态和自定义端点。</p>
</div>
<a rel="nofollow" href="/xiazai/skill6631" title="Spring Boot Actuator Analyzer" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/242/473/179621202443759.png?x-oss-process=image/resize,p_40" alt="Spring Boot REST 接口怎么实现流式响应"></p><pre class="brush:php;toolbar:false;">import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
@RestController
public class StreamController {
@GetMapping(value = "/stream", produces = "text/plain")
public ResponseEntity<streamingresponsebody> streamBytes() {
StreamingResponseBody body = outputStream -> {
String data = "Hello Stream\n";
for (int i = 0; i <p>这段代码演示了 <code>StreamingResponseBody</code> 的实现。与 <code>SseEmitter</code> 不同,这里没有显式的超时设置,连接的生命周期由 HTTP 请求的处理时长决定。写入操作直接作用于底层输出流,因此性能开销更小,但缺乏事件语义。如果需要推送结构化数据(如 JSON),通常需要在写入前手动序列化。这种模式适用于对延迟极其敏感且不需要复杂事件管理的场景。</p>
<h2>当使用 <code>Flux<string></string></code> 时如何处理背压问题</h2>
<p>在使用 <code>Flux<string></string></code> 进行流式响应时,如果生产者速度远快于消费者,会导致内存溢出,此时需要引入背压策略来控制数据流速。</p>
<pre class="brush:php;toolbar:false;">import reactor.core.publisher.Flux;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;
@RestController
public class ReactiveController {
@GetMapping(value = "/reactive-stream", produces = MediaType.TEXT_PLAIN_VALUE)
public Flux<string> reactiveStream() {
return Flux.interval(Duration.ofSeconds(1))
.map(i -> "Message " + i)
.onBackpressureBuffer(100); // 设置缓冲上限为 100
}
}</string>
此示例中,Flux.interval 产生数据的速度是固定的,而客户端的网络状况可能波动。通过 onBackpressureBuffer 操作符,我们设置了最大缓冲容量为 100。当缓冲区满时,新产生的元素会被丢弃,从而保护服务器内存不被撑爆。如果不设置背压策略,默认行为可能是丢弃最新元素或抛出异常,具体取决于 Flux 的构建方式。在实际生产中,应根据业务容忍度选择合适的背压策略,如 onBackpressureDrop 或 onBackpressureError。










