Spring Boot 集成 DeepSeek:2026 年最新完整指南
DeepSeek 是中国领先的开源大语言模型提供商(DeepSeek-V3、DeepSeek-R1 等),其 API 完全兼容 OpenAI 格式。这意味着你可以轻松在 Spring Boot 项目中使用它,尤其通过 Spring AI(Spring 官方 AI 集成框架)实现低代码接入。目前(2026 年 1 月),Spring AI 已原生支持 DeepSeek,包括专用 Starter。
集成 DeepSeek 的优势:
- 成本低(比 OpenAI 便宜得多)
- 性能强(推理能力接近 o1 系列)
- 支持聊天、函数调用、RAG 等
- 两种方式:云 API(推荐生产)或本地部署(Ollama,免费但需硬件)
前置准备:获取 DeepSeek API Key
- 访问 DeepSeek 开放平台:https://platform.deepseek.com/
- 注册/登录账号(支持邮箱或手机号)。
- 进入左侧菜单 API Keys → 点击 “创建 API Key”。
- 复制生成的 Key(以
sk-开头),安全保存(生产环境建议用环境变量)。
官方文档:https://api-docs.deepseek.com/
Base URL:https://api.deepseek.com(兼容 OpenAI)
方式一:推荐 – 使用 Spring AI(云 API,最简单)
Spring AI 提供了 spring-ai-openai-spring-boot-starter,通过配置 Base URL 和 Key 即可“伪装”成 OpenAI 调用 DeepSeek。Spring AI 最新版本已支持 DeepSeek 专用模型。
步骤1:创建 Spring Boot 项目
- 使用 https://start.spring.io/ 生成项目(Spring Boot 3.2+,Java 17+)。
- 添加依赖:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
<version>1.0.0</version> <!-- 或最新版 -->
</dependency>
步骤2:配置 application.yml
spring:
ai:
openai:
base-url: https://api.deepseek.com
api-key: sk-your-api-key-here # 推荐用环境变量 ${DEEPSEEK_API_KEY}
chat:
options:
model: deepseek-chat # 或 deepseek-reasoner (R1 推理模型)
temperature: 0.7
步骤3:创建服务类调用 LLM
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ai")
public class AiController {
private final ChatClient chatClient;
@Autowired
public AiController(ChatClient.Builder chatClientBuilder) {
this.chatClient = chatClientBuilder.build();
}
@GetMapping("/chat")
public String chat(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.call()
.content();
}
}
测试:启动项目,访问 http://localhost:8080/ai/chat?message=你好,DeepSeek!
输出 DeepSeek 的智能回复。
支持流式响应(Streaming):
@GetMapping(value = "/stream", produces = "text/event-stream")
public Flux<String> stream(@RequestParam String message) {
return chatClient.prompt()
.user(message)
.stream()
.content();
}
(需导入 reactor.core.publisher.Flux)
方式二:本地部署 DeepSeek(免费,无需 API Key)
使用 Ollama 运行 DeepSeek 开源模型(如 DeepSeek-R1),然后通过 Spring AI 的 Ollama Starter 集成。
步骤1:安装 Ollama
- 下载:https://ollama.com/
- 运行模型:
ollama run deepseek-r1(或 deepseek-v3)
步骤2:添加依赖
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-ollama-spring-boot-starter</artifactId>
</dependency>
步骤3:配置
spring:
ai:
ollama:
base-url: http://localhost:11434
chat:
options:
model: deepseek-r1
temperature: 0.7
服务类同上,无需 API Key。
注意事项与最佳实践
- 安全:API Key 绝不要硬编码,用环境变量或 Spring Cloud Config。
- 费用:DeepSeek 按 token 计费,远低于 OpenAI。
- 模型选择:
deepseek-chat:通用聊天deepseek-reasoner:高级推理(类似 o1)- 错误处理:添加重试机制(Resilience4j)。
- 生产优化:结合缓存、异步调用、RAG(检索增强)。
这个集成方案简单高效,适合构建 AI 问答、聊天机器人、智能助手等应用。
如果需要完整项目源码、流式响应前端实现或 RAG 扩展,随时告诉我,我继续帮你完善!🚀