news 2026/4/15 13:13:12

DeepSeek API 调用 - Spring Boot 实现

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
DeepSeek API 调用 - Spring Boot 实现

DeepSeek API 调用 - Spring Boot 实现

1. 项目依赖

pom.xml中添加以下依赖:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-webflux</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> </dependencies>
2. 项目结构
deepseek-project/ ├── src/main/java/com/example/deepseek/ │ ├── DeepSeekApplication.java │ ├── config/ │ │ └── DeepSeekConfig.java │ ├── model/ │ │ ├── ChatRequest.java │ │ ├── ChatResponse.java │ │ └── Message.java │ └── service/ │ └── DeepSeekService.java └── conversation.txt
3. 完整代码实现
3.1 配置类DeepSeekConfig.java
package com.example.deepseek.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration @Getter public class DeepSeekConfig { @Value("${deepseek.api.url}") private String apiUrl; @Value("${deepseek.api.key}") private String apiKey; }
3.2 请求/响应模型

Message.java:

package com.example.deepseek.model; import lombok.Data; @Data public class Message { private String role; private String content; }

ChatRequest.java:

package com.example.deepseek.model; import lombok.Data; import java.util.List; @Data public class ChatRequest { private String model = "deepseek-ai/DeepSeek-V3"; private List<Message> messages; private boolean stream = true; private int max_tokens = 2048; private double temperature = 0.7; private double top_p = 0.7; private int top_k = 50; private double frequency_penalty = 0.5; private int n = 1; private ResponseFormat response_format = new ResponseFormat("text"); @Data public static class ResponseFormat { private String type; public ResponseFormat(String type) { this.type = type; } } }

ChatResponse.java:

package com.example.deepseek.model; import lombok.Data; import java.util.List; @Data public class ChatResponse { private List<Choice> choices; @Data public static class Choice { private Delta delta; } @Data public static class Delta { private String content; } }
3.3 服务类DeepSeekService.java
package com.example.deepseek.service; import com.example.deepseek.config.DeepSeekConfig; import com.example.deepseek.model.ChatRequest; import com.example.deepseek.model.ChatResponse; import com.example.deepseek.model.Message; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.web.reactive.function.client.WebClient; import reactor.core.publisher.Flux; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.Scanner; @Service @RequiredArgsConstructor public class DeepSeekService { private final DeepSeekConfig config; private final WebClient.Builder webClientBuilder; private final ObjectMapper objectMapper = new ObjectMapper(); public void startInteractiveChat() { try (Scanner scanner = new Scanner(System.in); PrintWriter fileWriter = new PrintWriter(new FileWriter("conversation.txt", true))) { while (true) { System.out.print(" 请输入您的问题 (输入 q 退出): "); String question = scanner.nextLine().trim(); if ("q".equalsIgnoreCase(question)) { System.out.println("程序已退出"); break; } // 保存问题 saveToFile(fileWriter, question, true); // 发起对话请求 Flux<String> responseFlux = sendChatRequest(question); StringBuilder fullResponse = new StringBuilder(); responseFlux .doOnNext(chunk -> { System.out.print(chunk); fullResponse.append(chunk); }) .doOnComplete(() -> { // 保存完整回复 saveToFile(fileWriter, fullResponse.toString(), false); System.out.println(" ----------------------------------------"); fileWriter.println(" ----------------------------------------"); fileWriter.flush(); }) .blockLast(); } } catch (IOException e) { e.printStackTrace(); } } private Flux<String> sendChatRequest(String question) { ChatRequest request = new ChatRequest(); Message userMessage = new Message(); userMessage.setRole("user"); userMessage.setContent(question); request.setMessages(Collections.singletonList(userMessage)); return webClientBuilder.build() .post() .uri(config.getApiUrl()) .header("Authorization", "Bearer " + config.getApiKey()) .header("Content-Type", "application/json") .bodyValue(request) .retrieve() .bodyToFlux(String.class) .filter(line -> line.startsWith("data: ") && !line.equals("data: [DONE]")) .map(line -> { try { String jsonStr = line.substring(6); ChatResponse response = objectMapper.readValue(jsonStr, ChatResponse.class); return response.getChoices().get(0).getDelta().getContent(); } catch (Exception e) { return ""; } }) .filter(content -> !content.isEmpty()); } private void saveToFile(PrintWriter fileWriter, String content, boolean isQuestion) { String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); if (isQuestion) { fileWriter.printf(" [%s] Question: %s [%s] Answer: ", timestamp, content, timestamp); } else { fileWriter.print(content); } fileWriter.flush(); } }
3.4 主应用类DeepSeekApplication.java
package com.example.deepseek; import com.example.deepseek.service.DeepSeekService; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication public class DeepSeekApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(DeepSeekApplication.class, args); DeepSeekService deepSeekService = context.getBean(DeepSeekService.class); deepSeekService.startInteractiveChat(); } }
3.5 配置文件application.properties
deepseek.api.url=https://api.siliconflow.cn/v1/chat/completions deepseek.api.key=YOUR_API_KEY
4. 代码详解
4.1 关键特性
  1. 使用 Spring WebFlux 的响应式编程模型
  2. 流式处理 API 响应
  3. 文件记录对话
  4. 错误处理和异常管理
4.2 主要组件
  • DeepSeekConfig: 管理 API 配置
  • DeepSeekService: 处理对话逻辑和 API 交互
  • 模型类: 定义请求和响应结构
5. 使用方法
  1. 替换application.properties中的YOUR_API_KEY
  2. 运行DeepSeekApplication
  3. 在控制台输入问题
  4. 输入 ‘q’ 退出程序
  5. 查看conversation.txt获取对话记录
6. 性能和可扩展性
  • 使用响应式编程提高并发性能
  • 灵活的配置管理
  • 易于扩展和定制
7. 注意事项
  • 确保正确配置 API Key
  • 处理网络异常
  • 注意内存使用
总结

Spring Boot 实现提供了一个健壮、可扩展的 DeepSeek API 调用方案,利用响应式编程提供高效的流式对话体验。

立即体验

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/16 10:49:06

AI Agent架构解析:从感知-决策-执行闭环看新一代应用范式

以前我们做企业软件&#xff0c;最常见的交付物是“功能”&#xff1a;一个页面、一个按钮、一个报表、一个流程。用户买的是工具&#xff0c;工具怎么用、用得好不好&#xff0c;很大程度取决于人。 但这两年&#xff0c;很多团队开始意识到&#xff1a;真正值钱的不是工具本身…

作者头像 李华
网站建设 2026/4/12 5:57:21

基于SpringBoot的乡村支教管理系统(毕设源码+文档)

背景 本课题聚焦基于SpringBoot框架的乡村支教管理系统设计与实现&#xff0c;旨在解决传统乡村支教工作中志愿者招募与管理低效、支教资源调配不均、教学活动记录零散、支教效果评估不规范及各方沟通协同不足等问题。系统采用B/S架构&#xff0c;依托浏览器即可实现多端便捷访…

作者头像 李华
网站建设 2026/3/15 15:05:33

DVWA靶场通关——SQL Injection篇

一&#xff0c;Low难度下unionget字符串select****注入 1&#xff0c;首先手工注入判断是否存在SQL注入漏洞&#xff0c;输入1这是正常回显的结果&#xff0c;再键入1’ You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versio…

作者头像 李华
网站建设 2026/4/12 10:00:02

docker desktop安装redis

1.拉取redis镜像 docker hub直达 docker pull redis:latest查看镜像 PS C:WindowsSystem32> docker images REPOSITORY TAG IMAGE ID CREATED SIZE redis latest 0e403e3816e8 3 days ago 113MB mysql …

作者头像 李华
网站建设 2026/4/12 22:07:06

小程序 PHP_uniapp烩面店餐饮饭馆餐桌预订点餐系统的设计与实现_oa17g41j

目录系统设计目标技术架构核心功能模块创新点与优势应用价值项目开发技术介绍PHP核心代码部分展示系统结论源码获取/同行可拿货,招校园代理系统设计目标 该系统基于PHP和Uniapp框架开发&#xff0c;旨在为烩面店等中小型餐饮企业提供一体化的餐桌预订与点餐解决方案。设计目标…

作者头像 李华