Spring Boot 调用DeepSeek API的详细教程

news/2025/3/12 8:42:27/

目录

    • 前置准备
    • 步骤1:创建Spring Boot项目
    • 步骤2:配置API参数
    • 步骤3:创建请求/响应DTO
    • 步骤4:实现API客户端
    • 步骤5:创建控制器
    • 步骤6:异常处理
    • 步骤7:测试验证
      • 单元测试示例
      • Postman测试请求
    • 常见问题排查

本文将通过具体示例演示如何通过Spring Boot 2.7.2框架调用DeepSeek的API服务。我们将使用Java 11和最新的Spring Boot 2.7.2版本实现完整的集成流程。

前置准备

  1. 有效的DeepSeek API密钥(密钥注册地址)
  2. JDK 11或更高版本
  3. Maven 3.6.3
  4. Postman(用于API测试验证)
    详细可见官方DeepSeek API文档

步骤1:创建Spring Boot项目

通过Spring Initializr创建项目:

  • Project: Maven
  • Language: Java
  • Packaging: Jar
  • Java Version: 11
  • Dependencies:
    • Spring Web
    • Lombok
    • Jackson Databind
java">    <dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.3</version> <!-- 可替换为最新版本 --></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.20</version><scope>provided</scope>
</dependency>

步骤2:配置API参数

application.yml中添加配置:

deepseek:api:base-url: https://api.deepseek.com/v1chat-endpoint: /v1/chat/completionsapi-key: your_api_key_here

步骤3:创建请求/响应DTO

java">// 请求体
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ChatRequest {private String model;private List<Message> messages;private double temperature;@Data@Builder@NoArgsConstructor@AllArgsConstructorpublic static class Message {private String role;private String content;}
}// 响应体
@Data
public class ChatResponse {private String id;private String object;private long created;private List<Choice> choices;@Datapublic static class Choice {private Message message;private int index;private String finish_reason;@Datapublic static class Message {private String role;private String content;}}
}

步骤4:实现API客户端

java">package com.tianwen.service.impl;import com.tianwen.deepseekDTO.ChatRequest;
import com.tianwen.deepseekDTO.ChatResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.reactive.function.client.WebClient;import javax.annotation.PostConstruct;@Service
public class DeepSeekLegacyClient {@Value("${deepseek.api.api-key}")private String apiKey;@Value("${deepseek.api.base-url}")private String baseUrl;private RestTemplate restTemplate;@Autowiredprivate RestTemplateBuilder builder;@PostConstruct  // 确保依赖注入完成后执行public void init() {this.restTemplate = builder.rootUri(baseUrl).defaultHeader("Authorization", "Bearer " + apiKey).build();}public DeepSeekLegacyClient(RestTemplateBuilder builder) {this.restTemplate = builder.rootUri(baseUrl).defaultHeader("Authorization", "Bearer " + apiKey).build();}public ChatResponse chatCompletion(ChatRequest request) {String fullUrl = baseUrl + "/chat/completions";  // 手动拼接完整路径HttpEntity<ChatRequest> entity = new HttpEntity<>(request);ResponseEntity<ChatResponse> response = restTemplate.postForEntity(fullUrl,entity,ChatResponse.class);return response.getBody();}
}@Configuration
public class WebClientConfig {@Value("${deepseek.api.base-url}")private String baseUrl;@Value("${deepseek.api.api-key}")private String apiKey;@Beanpublic WebClient webClient() {return WebClient.builder().baseUrl(baseUrl).defaultHeader("Authorization", "Bearer " + apiKey).defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).build();}
}

步骤5:创建控制器

java">@RestController
@RequestMapping("/api/chat")
@RequiredArgsConstructor
public class ChatController {private final DeepSeekClient deepSeekClient;@PostMappingpublic ResponseEntity<ChatResponse> chat(@RequestBody ChatRequest request) {return ResponseEntity.ok(deepSeekClient.chatCompletion(request));}
}

步骤6:异常处理

全局异常处理器:

java">@RestControllerAdvice
public class GlobalExceptionHandler {// 修改WebClient异常处理@ExceptionHandler(WebClientResponseException.class)public ResponseEntity<String> handleWebClientErrors(WebClientResponseException ex) {return ResponseEntity.status(ex.getRawStatusCode()).body("API Communication Error: " + ex.getResponseBodyAsString());}
}

步骤7:测试验证

单元测试示例

java">@SpringBootTest
class DeepSeekClientTest {@Autowiredprivate DeepSeekClient client;@Testvoid testChatCompletion() {ChatRequest request = ChatRequest.builder().model("deepseek-chat").temperature(0.7).messages(List.of(new ChatRequest.Message("user", "你好,介绍一下你自己"))).build();ChatResponse response = client.chatCompletion(request);assertNotNull(response);assertFalse(response.getChoices().isEmpty());}
}

Postman测试请求

POST http://localhost:8080/api/chat
Headers:
Content-Type: application/jsonBody:
{"messages": [{"content": "如何学习java编程?","role": "user"}],"model": "deepseek-chat","temperature": 0.7
}

常见问题排查

  1. 401 Unauthorized

    • 检查API密钥有效性
    • 验证Authorization头部格式
  2. 序列化错误

    • 确认DTO字段命名与API文档一致
    • 检查Jackson注解配置
  3. 超时问题

    • 调整连接超时设置
    • 检查网络防火墙配置
  4. 速率限制

    • 实现令牌桶限流算法
    • 监控X-RateLimit-*响应头
  5. 402 Payment Required 错误

    • API账户余额耗尽
    • API密钥未绑定有效支付方式
    • 请求参数触发了计费规则
    • ​模型调用超出免费额度

http://www.ppmy.cn/news/1578560.html

相关文章

stm32 基于蓝桥物联网赛 oled屏使用

oled屏是物联网赛道必考的题目&#xff0c;其综合了I2C协定等等知识&#xff0c;不讲原理&#xff0c;纯讲应用&#xff0c;现在开始。 补充资源代码 资源包给我们的代码是不全的&#xff0c;比如oled屏中的OLED_Write函数并没有定义&#xff0c;因此我们需要先将该函数补全。…

【python高并发】高速将图片提交到flask、fastapi等主流服务框架

一、摘要 高性能,高并发的读取图片,并将图片传输到服务器的应用场景很多,比如上传图片到网站,将图片提交到后台推理等。这篇文章实现一种多线程并发方式将图片提交到后台。 二、多线程发送请求的实现方法 1. 使用ThreadPoolExecutor线程池 通过线程池管理并发请求,避免…

【前端基础】:HTML

认识 HTML 标签 HTML 代码是由 “标签” 构成的. 形如: <body>hello</body>标签名 (body) 放到 <> 中 大部分标签成对出现. 为开始标签, 为结束标签 少数标签只有开始标签, 称为 “单标签”. 开始标签和结束标签之间, 写的是标签的内容. (hello) 开始标签中…

正则表达式快速入门

原文链接&#xff1a;https://kashima19960.github.io/2025/03/10/正则表达式快速入门/ 前言 我写这篇文章&#xff0c;用来记录我平时使用正则表达式的方法&#xff0c;这样我在分享知识给大家的同时&#xff0c;也复习了一遍正则表达式。在你学习某个知识的时候&#xff0c;…

前端开发中的设计模式:观察者模式的应用与实践

1. 引言 1.1 设计模式的重要性 设计模式是软件开发中经过验证的解决方案&#xff0c;能够帮助开发者解决常见的设计问题。在前端开发中&#xff0c;合理使用设计模式可以提高代码的可维护性、可扩展性和复用性。 1.2 本文的目标 本文旨在深入探讨观察者模式在前端开发中的应…

Python数据分析之机器学习基础

Python 数据分析重点知识点 本系列不同其他的知识点讲解&#xff0c;力求通过例子让新同学学习用法&#xff0c;帮助老同学快速回忆知识点 可视化系列&#xff1a; Python基础数据分析工具数据处理与分析数据可视化机器学习基础 五、机器学习基础 了解机器学习概念、分类及…

HTML左右分页2【搬代码】

HTML左右分页2 html <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>左右分页布局</title>&l…

清华同方国产电脑能改windows吗_清华同方国产系统改win7教程

清华同方国产电脑能改windows吗&#xff1f;清华同方国产电脑如果采用的是兆芯kx-6000系列或kx-7000系列以及海光c86 3250 3350 X86架构处理器可以安装windows。在安装win7时bios中要关闭“安全启动”和开启legacy传统模式支持&#xff0c;如果是NVME接口的固态硬盘&#xff0c…