当“AI 能力”成为应用标配,Java 开发者面临的核心课题不再是“会不会调 API”,而是如何将大模型服务高效、稳定、可观测地集成进 SpringBoot 微服务体系。本文以 OpenAI 兼容接口为例,从工程化视角拆解客户端封装、流式响应、异步编排与容错设计,帮助 Java 工程师避开“能跑但撑不住生产”的陷阱。
大模型接口天然适合响应式处理:单次请求可能耗时数十秒,若用 RestTemplate 同步阻塞,线程池将瞬间被打满。Spring WebFlux 的 WebClient 支持非阻塞 IO,并且能无缝处理 SSE 流式返回。即便你的项目仍基于 SpringMVC,也可以引入 WebFlux 依赖并仅在 HTTP 客户端层使用 WebClient,不会影响既有的 Servlet 容器。
Maven 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>大模型的 API Key、Base URL、模型名称、超时时间等必须外置。使用 @ConfigurationProperties 实现强类型绑定:
llm:
base-url: https://api.openai.com/v1
api-key: ${LLM_API_KEY}
model: gpt-4o-mini
temperature: 0.7
max-tokens: 2048
connect-timeout-ms: 3000
read-timeout-ms: 60000@Data
@Component
@ConfigurationProperties(prefix = "llm")
public class LLMProperties {
private String baseUrl;
private String apiKey;
private String model;
private Double temperature;
private Integer maxTokens;
private Integer connectTimeoutMs;
private Integer readTimeoutMs;
}禁止在代码中硬编码密钥,建议使用环境变量注入,并在日志中过滤敏感字段。
定义通用 DTO,避免与具体厂商 SDK 耦合:
@Data
@Builder
public class ChatMessage {
private String role; // system / user / assistant
private String content;
}
@Data
@Builder
public class ChatRequest {
private String model;
private List<ChatMessage> messages;
private Double temperature;
private Integer maxTokens;
@Builder.Default
private Boolean stream = false;
}
@Data
public class ChatResponse {
private String content;
private Integer promptTokens;
private Integer completionTokens;
}封装 LLMClient 组件,提供同步、流式两种调用入口。WebClient 要求显式设置请求头:
@Service
@RequiredArgsConstructor
public class LLMClient {
private final LLMProperties props;
private WebClient webClient;
@PostConstruct
void init() {
this.webClient = WebClient.builder()
.baseUrl(props.getBaseUrl())
.defaultHeader("Authorization", "Bearer " + props.getApiKey())
.defaultHeader("Content-Type", "application/json")
.build();
}
// 同步调用(内部仍非阻塞,通过 block 获取结果)
public ChatResponse chatSync(List<ChatMessage> messages) {
ChatRequest request = ChatRequest.builder()
.model(props.getModel())
.messages(messages)
.temperature(props.getTemperature())
.maxTokens(props.getMaxTokens())
.build();
return webClient.post()
.uri("/chat/completions")
.bodyValue(request)
.retrieve()
.bodyToMono(JsonNode.class)
.map(this::parseResponse)
.timeout(Duration.ofMillis(props.getReadTimeoutMs()))
.block();
}
}解析响应时需处理 JSON 中的 choices[0].message.content,注意对空值做好保护。使用 JsonNode 可避免为每个厂商响应创建独立 Pojo。
生产级应用必须优先使用流式接口,因为大模型生成时间远大于网络传输时间,用户等待首字的时间直接决定体验。OpenAI 兼容接口通过 POST /chat/completions 并设置 stream: true 返回 text/event-stream。WebClient 接收方法:
public Flux<String> chatStream(List<ChatMessage> messages) {
ChatRequest request = ChatRequest.builder()
.model(props.getModel())
.messages(messages)
.temperature(props.getTemperature())
.maxTokens(props.getMaxTokens())
.stream(true) // 关键!
.build();
return webClient.post()
.uri("/chat/completions")
.bodyValue(request)
.retrieve()
.bodyToFlux(ServerSentEvent.class)
.mapNotNull(event -> {
String data = (String) event.data();
if (data == null || "[DONE]".equals(data.trim())) return null;
// 解析 data 为 JSON,提取 delta.content
return extractDelta(data);
})
.timeout(Duration.ofMillis(props.getReadTimeoutMs()))
.onErrorResume(e -> Flux.empty());
}注意:使用 bodyToFlux(ServerSentEvent.class) 时,Spring 会将 SSE 分帧后的数据自动解析为 ServerSentEvent 对象。若要更底层控制,也可以直接使用 bodyToFlux(String.class) 手动按行切分。核心是提取 choices[0].delta.content,可能为 null 但不要忽略 finish_reason。
在 Controller 中将 Flux<String> 直接返回,Spring WebFlux 会自动将其按 SSE 格式输出,前端即可通过 EventSource 或 fetch + ReadableStream 消费:
@GetMapping("/chat/stream")
public Flux<String> stream(@RequestParam String prompt) {
List<ChatMessage> messages = List.of(
ChatMessage.builder().role("user").content(prompt).build()
);
return llmClient.chatStream(messages);
}真实场景下,同一 prompt 的重复调用会造成成本浪费;大模型 API 也可能因流量高峰而返回 429。工程化方案至少包含三点:
@Cacheable(cacheNames = "llmCache", key = "#messages.hashCode()")
public ChatResponse chatSyncWithCache(List<ChatMessage> messages) { ... }注意流式接口不能直接加缓存,但可对完整内容缓存,流式输出结束后写入缓存。
ExchangeFilterFunction 在客户端层统一注入重试逻辑:ExchangeFilterFunction retryFilter = (request, next) ->
next.exchange(request).retryWhen(Retry.backoff(3, Duration.ofSeconds(1))
.filter(throwable -> throwable instanceof WebClientRequestException));@CircuitBreaker 注解,当大模型服务连续失败时返回预设话术或走本地小模型兜底,确保主业务流程不中断。大模型调用是外部依赖,必须纳入监控。使用 Micrometer 记录调用耗时、成功/失败次数,并在日志中输出请求摘要(注意清除敏感信息)。例如:
Timer.Sample sample = Timer.start(meterRegistry);
try {
// 调用逻辑
sample.stop(timer);
} catch (Exception e) {
sample.stop(failureTimer);
}也可以结合 Sleuth/OpenTelemetry,在 WebClient 请求头中注入 traceId,便于跨系统排查延迟和错误。
SpringBoot 对接大模型服务的本质,是把一个尚不稳定的外部“智能组件”纳入成熟的 Java 工程体系。通过 WebClient 实现响应式调用、SSE 打造流畅对话体验、再辅以缓存/限流/熔断和监控,Java 开发者完全有能力将 AI 能力做成可靠的生产级功能。技术栈会变,但工程化的底层思考——资源可控、体验流畅、故障隔离——永远不会过时。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。