本文将以清晰的步骤说明如何通过 Spring Boot 调用 DeepSeek API,并提供完整的代码示例。从 API 密钥获取到项目部署,涵盖所有关键环节。
一、准备工作
1.1 注册 DeepSeek 开发者账号
- 访问 DeepSeek 开发者平台
- 点击 Sign Up 完成注册(支持邮箱或 GitHub 账号)
- 验证邮箱并登录控制台
1.2 创建应用并获取 API Key
- 进入控制台,点击 Create New App
- 填写应用信息(名称、描述等)
- 在 API Keys 页面生成新密钥
- 复制并妥善保存 API Key(仅显示一次)
二、创建 Spring Boot 项目
2.1 初始化项目
使用 Spring Initializr 创建项目:
- Project: Maven
- Language: Java
- Dependencies:
-
- Spring Web
- Lombok(简化代码)
- Configuration Processor(配置提示)
<!-- pom.xml 核心依赖 -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2.2 配置 API 信息
application.yml
deepseek:
api:
base-url: https://api.deepseek.com/v1
chat-endpoint: /chat/completions
api-key: ${DEEPSEEK_API_KEY} # 从环境变量读取
三、核心代码实现
3.1 配置类(管理 API 参数)
@Configuration
@ConfigurationProperties(prefix = "deepseek.api")
@Data
public class DeepSeekConfig {
private String baseUrl; // API 基础地址
private String chatEndpoint; // 聊天接口路径
private String apiKey; // 认证密钥
}
3.2 请求/响应 DTO
// 请求体
@Data
@Builder
public class ApiRequest {
private String model;
private List<Message> messages;
private Double temperature;
@Data
@Builder
public static class Message {
private String role;
private String content;
}
}
// 响应体
@Data
public class ApiResponse {
private List<Choice> choices;
@Data
public static class Choice {
private Message message;
}
@Data
public static class Message {
private String content;
}
}
3.3 服务层(API 调用逻辑)
@Service
@RequiredArgsConstructor
public class AIService {
private final DeepSeekConfig config;
private final WebClient webClient;
public String generateText(String prompt) {
// 构建请求体
ApiRequest request = ApiRequest.builder()
.model("deepseek-chat")
.messages(List.of(
new ApiRequest.Message("user", prompt)
))
.temperature(0.7)
.build();
// 发送请求并处理响应
return webClient.post()
.uri(config.getChatEndpoint())
.header(HttpHeaders.AUTHORIZATION, "Bearer " + config.getApiKey())
.bodyValue(request)
.retrieve()
.bodyToMono(ApiResponse.class)
.map(res -> res.getChoices().get(0).getMessage().getContent())
.block();
}
}
3.4 控制器(提供 REST 接口)
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AIController {
private final AIService aiService;
@PostMapping("/generate")
public ResponseEntity<?> generate(@RequestBody Map<String, String> request) {
try {
String response = aiService.generateText(request.get("prompt"));
return ResponseEntity.ok(Map.of("result", response));
} catch (Exception e) {
return ResponseEntity.internalServerError()
.body(Map.of("error", e.getMessage()));
}
}
}
四、配置 HTTP 客户端
@Bean
public WebClient webClient(DeepSeekConfig config) {
return WebClient.builder()
.baseUrl(config.getBaseUrl())
.defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
}
五、运行与测试
5.1 设置环境变量
# Linux/macOS
export DEEPSEEK_API_KEY=your_api_key_here
# Windows
set DEEPSEEK_API_KEY=your_api_key_here
5.2 启动应用
mvn spring-boot:run
5.3 发送测试请求
curl -X POST http://localhost:8080/api/ai/generate \
-H "Content-Type: application/json" \
-d '{"prompt":"用Java实现快速排序"}'
预期响应:
{
"result": "public class QuickSort {\n public static void sort(int[] arr) {\n // 排序算法实现...\n }\n}"
}
六、增强功能(可选)
6.1 请求重试机制
.retryWhen(Retry.backoff(3, Duration.ofSeconds(1)))
6.2 超时控制
.timeout(Duration.ofSeconds(30))
6.3 敏感信息加密
使用 Jasypt 加密 API Key:
deepseek:
api:
api-key: ENC(加密后的密钥)
七、完整项目结构
deepseek-demo/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ ├── config/ # 配置类
│ │ │ ├── controller/ # 接口定义
│ │ │ ├── dto/ # 请求/响应模型
│ │ │ ├── service/ # 业务逻辑
│ │ │ └── Application.java
│ │ └── resources/
│ │ ├── application.yml # 配置文件
│ └── test/ # 单元测试
八、常见问题排查
| 问题现象 | 解决方案 |
|---|---|
| 401 Unauthorized | 检查 API Key 是否有效/过期 |
| 404 Not Found | 确认接口路径是否正确 |
| 响应解析失败 | 检查 DTO 结构与文档是否一致 |
| 环境变量未生效 | 重启 IDE 或终端 |