当 Java 遇见国产大模型
SpringAI 作为 Spring 生态中面向 AI 能力的集成框架,近期正式宣布对国产大模型 DeepSeek 的直连支持——这意味着我们终于可以像使用 OpenAI 一样,以标准化方式在 Java 项目中调用国产大模型!
这篇文章和以往的系列文章无关,属于快速查找型的文章,主要服务以下内容:
快速理解 SpringAI 的抽象设计哲学
快速配置 DeepSeek 直连通道
快速实现完整的对话与流式响应
简略生产环境最佳实践
一、SpringAI 的设计哲学
1.1 统一的 API 抽象
SpringAI 的核心价值在于统一不同 AI 供应商的差异化 API。无论是 OpenAI、Azure 还是 DeepSeek,开发者都通过同一套 ChatClient 接口进行操作:
public interface ChatClient {
ChatResponse call(ChatRequest request);
Flux<ChatResponse> stream(ChatRequest request);
}
这种设计完美契合六边形架构思想,将 AI 能力作为可插拔的端口(Port)接入系统,业务核心逻辑则通过适配器(Adapter)与具体实现解耦。
1.2 配置即连接
通过 Spring Boot 的 application.yml,我们可以灵活切换不同 AI 供应商:
spring:
ai:
provider: deepseek # 只需修改这个值即可切换供应商
deepseek:
base-url: https://api.deepseek.com/v1
api-key: ${DEEPSEEK_API_KEY}
这种配置方式与 Spring Security 的认证体系、Spring Cloud 的微服务配置中心天然契合,特别适合需要动态切换模型供应商的企业场景。
二、快速接入 DeepSeek
2.1 添加依赖
在 pom.xml 中引入 SpringAI 的 DeepSeek 模块:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-deepseek</artifactId>
<version>0.8.1</version>
</dependency>
2.2 配置连接参数
在 application.yml 中配置 DeepSeek 的访问凭证:
spring:
ai:
deepseek:
base-url: https://api.deepseek.com/v1
api-key: sk-your-api-key-here
chat:
options:
model: deepseek-chat
temperature: 0.7
这里我们启用了配置继承机制:全局配置可被具体 Chat 选项覆盖,实现不同业务场景的参数调优。
2.3 实现基础对话
创建服务层组件:
@Service
@RequiredArgsConstructor
public class DeepSeekService {
private final DeepSeekChatClient chatClient;
public String generateContent(String prompt) {
Prompt request = new Prompt(new UserMessage(prompt));
return chatClient.call(request).getResult().getOutput().getContent();
}
}
在 Controller 层暴露 API:
@RestController
@RequestMapping("/api/ai")
public class AIController {
private final DeepSeekService deepSeekService;
@PostMapping("/ask")
public ResponseEntity<String> askQuestion(@RequestBody String question) {
String answer = deepSeekService.generateContent(question);
return ResponseEntity.ok(answer);
}
}
三、进阶功能实现
3.1 流式响应
对于需要实时反馈的场景,使用 Server-Sent Events (SSE) 实现流式传输:
@GetMapping("/stream")
public Flux<String> streamResponse(@RequestParam String prompt) {
return chatClient.stream(new Prompt(prompt))
.map(response -> response.getResult().getOutput().getContent());
}
前端通过 EventSource 监听:
const eventSource = new EventSource('/api/ai/stream?prompt=如何设计分布式系统');
eventSource.onmessage = (e) => {
console.log(e.data); // 实时获取片段
};
3.2 结构化输出
通过指定响应格式,让模型返回结构化数据:
@Bean
public PromptTemplate userPromptTemplate() {
return new PromptTemplate("""
请将以下用户反馈分类:
{feedback}
按 JSON 格式返回:
{
"category": "bug|feature|compliment",
"severity": 1-5
}
""");
}
public AnalysisResult analyzeFeedback(String feedback) {
Prompt prompt = userPromptTemplate().create(Map.of("feedback", feedback));
String json = chatClient.call(prompt).getResult().getOutput().getContent();
return objectMapper.readValue(json, AnalysisResult.class);
}
四、生产环境最佳实践
4.1 安全加固
在 Spring Security 配置中保护 AI 端点:
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/ai/**").hasRole("AI_USER")
)
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
return http.build();
}
4.2 AI 也有的性能调优
通常默认配置都可以满足要求,但是当需要调优时,修改以下参数即可自定义配置。
spring:
ai:
deepseek:
client:
connect-timeout: 5s
read-timeout: 30s
max-connections: 50
4.3 监控告警
推荐使用 Micrometer 集成监控指标,代码非常简单如下所示:
@Bean
MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> registry.config()
.commonTags("ai.provider", "deepseek");
}
五、架构思考:AI 如何融入现有系统
在典型的领域驱动服务架构中,建议将 AI 服务定位在应用层与领域层之间:
用户界面层
↓
应用服务层 → AI 服务代理(处理 prompt 工程)
↓
领域模型层
↓
基础设施层(SpringAI 实现)
这种设计保证了:
领域模型不依赖具体 AI 实现
应用服务控制 AI 的上下文组装
基础设施层实现技术细节
结语
通过 SpringAI 集成 DeepSeek,我们不仅获得了大模型的能力,更重要的是遵循了可持续演进的架构原则。这样的架构刚好帮助我们逐步推进下面的架构设计原则:
将 AI 调用封装为领域服务
为重要 AI 操作添加审计日志
定期评估模型输出的业务一致性
通过上面的快速预览内容,你应该可以对整体 SpringAI 的功能做一个简略了解。今后的文章中,我们将详细阐述 DDD 和 SpringAI 的真正实战型内容,敬请期待。