大模型一次完整回答通常需要十几秒,如果后端等全部生成完再返回,用户会面对长时间空白。流式输出把"等待一个结果"变成"持续接收一批增量",体验差别非常明显。本文只解决一条链路:Java 服务端如何从兼容 OpenAI Chat Completions 协议的上游拉取流式增量,再通过 SSE(Server-Sent Events)逐字推送给浏览器。示例基于 Java 17、Spring Boot 3 与 WebFlux,密钥统一通过环境变量注入。
1. 先确定技术边界
SSE 是单向推送:服务端到客户端。它基于普通 HTTP,浏览器原生 EventSource 即可接入,断线可自动重连,适合"模型一边生成、页面一边显示"的场景。若需要双向高频交互(例如语音打断、多人协同白板),才需要考虑 WebSocket。
链路分三段:浏览器用 GET 建立 SSE 连接 → Spring WebFlux 控制器返回一个 Flux<ServerSentEvent<String>> → WebClient 以 text/event-stream 订阅上游,把每个 chunk 中的 choices[0].delta.content 提取出来。任一段使用阻塞式 API,流式都会退化成一次性返回。
2. 依赖与配置
只需 WebFlux 与 Jackson,不需要额外 SSE 依赖:
xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
application.yml 中集中放置上游地址、模型名与密钥占位符:
yaml
server:
port: 8080
llm:
base-url: ${LLM_BASE_URL:https://api.openai.com/v1}
api-key: ${LLM_API_KEY}
model: ${LLM_MODEL:gpt-4o-mini}
LLM_API_KEY 必须由部署环境注入,禁止写入配置文件或提交到代码仓库。
3. 理解上游的流式协议
请求体中增加 "stream": true 后,上游不再返回单个 JSON 对象,而是持续返回形如 data: {...}\n\n 的事件。关键字段有三处:增量文本位于 choices[0].delta.content,首包可能只有 role 而没有 content,结束标志是独立一行 data: [DONE]。[DONE] 不是合法 JSON,必须在反序列化之前拦截。
用 Java 17 的 record 描述载荷,并忽略上游后续新增字段:
java
@JsonInclude(JsonInclude.Include.NON_NULL)
record ChatRequest(String model, List<Message> messages,
boolean stream, double temperature) { }
record Message(String role, String content) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record ChatChunk(List<Choice> choices) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record Choice(Delta delta) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record Delta(String content) { }
4. 服务端完整实现
下面的单文件包含启动类、WebClient 配置、服务层与控制器。要点有三个:一是 WebClient 必须声明 Accept: text/event-stream,否则响应体会被当成普通 JSON 解码;二是用 takeUntil 截断结束标记;三是把每个增量包装成带 event 名称的 ServerSentEvent,便于前端分类处理。
java
package com.lbl.ai.stream;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.http.client.HttpClient;
import java.time.Duration;
import java.util.List;
/**
* @Author : libolin
*/
@SpringBootApplication
public class StreamApplication {
public static void main(String[] args) {
SpringApplication.run(StreamApplication.class, args);
}
@Bean
WebClient llmWebClient(WebClient.Builder builder,
@Value("${llm.base-url}") String baseUrl) {
HttpClient httpClient = HttpClient.create()
.connectTimeout(Duration.ofSeconds(5))
.responseTimeout(Duration.ofSeconds(120));
return builder
.clientConnector(new ReactorClientHttpConnector(httpClient))
.baseUrl(baseUrl)
.build();
}
}
@Service
class LlmStreamService {
private static final String DONE = "[DONE]";
private static final Logger log = LoggerFactory.getLogger(LlmStreamService.class);
private final WebClient webClient;
private final ObjectMapper objectMapper;
private final String apiKey;
private final String model;
LlmStreamService(WebClient llmWebClient, ObjectMapper objectMapper,
@Value("${llm.api-key}") String apiKey,
@Value("${llm.model}") String model) {
this.webClient = llmWebClient;
this.objectMapper = objectMapper;
this.apiKey = apiKey;
this.model = model;
}
Flux<ServerSentEvent<String>> stream(String question) {
ChatRequest request = new ChatRequest(
model, List.of(new Message("user", question)), true, 0.7);
return webClient.post()
.uri("/chat/completions")
.header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.TEXT_EVENT_STREAM)
.bodyValue(request)
.retrieve()
.onStatus(HttpStatusCode::isError, response ->
response.bodyToMono(String.class)
.defaultIfEmpty("")
.flatMap(body -> Mono.error(new IllegalStateException(
"LLM HTTP " + response.statusCode() + ": " + body))))
.bodyToFlux(String.class)
.takeUntil(DONE::equals)
.filter(raw -> !DONE.equals(raw) && StringUtils.hasText(raw))
.map(this::extractDelta)
.filter(StringUtils::hasText)
.map(text -> ServerSentEvent.<String>builder(text).event("delta").build())
.concatWith(Mono.just(
ServerSentEvent.<String>builder("[DONE]").event("done").build()))
.timeout(Duration.ofSeconds(120))
.doOnCancel(() -> log.info("client disconnected, upstream cancelled"))
.doOnError(error -> log.warn("stream failed", error))
.onErrorResume(error -> Mono.just(ServerSentEvent.<String>builder(
"上游异常:" + error.getMessage()).event("error").build()));
}
private String extractDelta(String raw) {
try {
ChatChunk chunk = objectMapper.readValue(raw, ChatChunk.class);
if (chunk.choices() == null || chunk.choices().isEmpty()) {
return "";
}
Delta delta = chunk.choices().get(0).delta();
return delta == null ? "" : delta.content();
} catch (JsonProcessingException e) {
log.warn("ignore malformed chunk: {}", raw);
return "";
}
}
}
@RestController
class StreamController {
private final LlmStreamService streamService;
StreamController(LlmStreamService streamService) {
this.streamService = streamService;
}
@GetMapping(value = "/api/ai/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<ServerSentEvent<String>> stream(@RequestParam String q) {
return streamService.stream(q);
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
record ChatRequest(String model, List<Message> messages,
boolean stream, double temperature) { }
record Message(String role, String content) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record ChatChunk(List<Choice> choices) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record Choice(Delta delta) { }
@JsonIgnoreProperties(ignoreUnknown = true)
record Delta(String content) { }
启动后可用 curl -N 'http://localhost:8080/api/ai/stream?q=用三句话解释JVM堆和栈的区别' 验证,终端会看到连续到达的 event: delta 数据块。
5. 前端接入与方案对比
浏览器端不需要任何第三方库:
javascript
const box = document.getElementById('answer');
const es = new EventSource('http://localhost:8080/api/ai/stream?q=你好');
es.addEventListener('delta', e => { box.textContent += e.data; });
es.addEventListener('done', () => es.close());
es.addEventListener('error', e => { box.textContent += '\n[错误] ' + e.data; });
选择推送方式时,可按下面这张表判断:
| 方案 | 首字延迟 | 双向通信 | 实现复杂度 | 适用场景 |
|---|---|---|---|---|
| 一次性 JSON | 高,等待全文生成 | 不支持 | 低 | 后台批处理、非交互摘要 |
| SSE | 低,边生成边推送 | 单向 | 低,浏览器原生 | 聊天、问答、逐字展示 |
| WebSocket | 低 | 支持 | 高,需连接管理 | 语音打断、多人协作 |
| 前端轮询 | 取决于间隔 | 伪双向 | 中 | 兼容老旧网关、短任务进度 |
6. 踩坑记录
- 忘记设置
Accept: text/event-stream:bodyToFlux(String.class)会按普通响应处理,报"无法反序列化数组"或一次性返回全部内容。 - 先反序列化再判断
[DONE]:结束标记不是 JSON,readValue会直接抛异常;必须先takeUntil截断。 - 首包
delta.content为 null :它通常只携带role,必须过滤空字符串,否则前端会插入无意义空白。 EventSource只支持 GET :需要携带复杂请求体时改用fetch+ReadableStream,或在服务端用查询参数/会话 ID 传递上下文。- 反向代理缓冲吞掉流式效果 :Nginx 需配置
proxy_buffering off,并确认响应链路未开启会缓冲整个响应的压缩中间件。 - 超时值要大于正常生成时长 :示例中
responseTimeout为 120 秒;设得过短会让长回答被截断,设得过长则会拖住异常连接。
小结
流式输出不是前端动画,而是一条需要端到端配合的数据通道:服务端用非阻塞客户端拉取上游增量,用 takeUntil 处理协议边界,再通过 Flux<ServerSentEvent<String>> 推送;浏览器用原生 EventSource 按事件类型渲染。这套实现的价值在于边界清晰------上游协议变化只影响 DTO 与提取方法,推送方式变化只影响控制器,业务逻辑无需改动。后续可在此基础上补上 token 计量、断线续传与背压控制,把"能流式"升级为"可运营的流式"。