找回密码
 立即注册
首页 业界区 业界 如何用Forest方便快捷地在SpringBoot项目中对接DeepSeek ...

如何用Forest方便快捷地在SpringBoot项目中对接DeepSeek

暴灵珊 2025-6-1 23:35:09
 一. 环境要求


  • JDK 8 / 17
  • SpringBoot 2.x / 3.x
  • Forest 1.6.4+
  • Fastjson2
依赖配置

除了 SpringBoot 和 Lombok 等基础框架之外,再加上 Forest 和 Fastjson2 的依赖
  1. <dependency>
  2.     <groupId>com.dtflys.forest</groupId>
  3.     forest-spring-boot-starter</artifactId>
  4.     <version>1.6.4</version>
  5. </dependency>
  6. <dependency>
  7.     <groupId>com.alibaba</groupId>
  8.     fastjson</artifactId>
  9.     <version>2.0.53</version>
  10. </dependency>
复制代码
1.gif
二. 申请 DeepSeek 的 API Key

打开 DeepSeek 官网,进入到 API Key 的管理页面(DeepSeek),就能找到您的 API Key。
如果还没有 KEY,可以点击页面下方的创建API Key按钮

 
创建完之后,会弹出一个对话框告诉您新生成的 API Key 字符串,然后要及时把它复制下来保存到一个安全的地方。
三. 配置项目

进入 SpringBoot 的配置文件application.yml,加入以下代码:
  1. # Forest 框架配置
  2. forest:
  3.   connect-timeout: 10000      # 请求连接超时时间
  4.   read-timeout: 3600000       # 请求数据读取超时时间,越长越好
  5.   variables:
  6.     apiKey: YOUR_API_KEY      # 替换为您申请到的 API Key
  7.     model: deepseek-reasoner  # DeepSeek 支持的模型,R1 模型
复制代码
3.gif
四. 创建声名式接口

Forest 支持以声名式的方式发送 HTTP 请求,以下代码就是将 DeepSeek API 请求以声名式接口的方式进行定义
  1. public interface DeepSeek {
  2.    
  3.     @Post(
  4.             url = "https://api.deepseek.com/chat/completions",
  5.             contentType = "application/json",
  6.             headers = "Authorization: Bearer {apiKey}",
  7.             data = "{"messages":[{"content":"{content}","role":"user"}],"model":"{model}","stream":true}")
  8.     ForestSSE completions(@Var("content") String content);
  9. }
复制代码
4.gif
以上的代码意思也很明显,调用该接口方法就会发送一个POST请求,URL 地址为 https://api.deepseek.com/chat/completions
其中 {apiKey} 和 {model} 的意思为读取配置文件中的 apiKey 字段,{content} 则是读取 @Var("content") 注解修饰的参数。 并且请求体数据为官网文档提供的 JSON 字符串,然后通过{变量名}这种字符串模板占位符的形式拼接出您想要的参数。
接口方法的返回类型为ForestSSE,这是 Forest 框架提供的内置类型,主要用于接受和处理 SSE 事件流消息。
五. 调用接口

在声名式接口创建完之后,可以通过 Spring 的@Resouce注解将此接口实例注入到启动类中,Forest框架会利用动态代理模式自动生成相应的接口代理类实例,并将其自动注入到您所需要调用的类中。
  1. @Resource
  2. private DeepSeek deepSeek;
复制代码
5.gif
然后就可以调用接口进行发送请求的操作了,并设置Lambda表达式来接收和处理返回的 SSE 流式事件消息
  1. @SpringBootApplication
  2. public class DeepSeekExampleApplication implements CommandLineRunner {
  3.     // DeepSeek 声名式接口
  4.     @Resource
  5.     private DeepSeek deepSeek;
  6.     @Override
  7.     public void run(String... args) {
  8.         // 调用声明式接口方法
  9.         deepSeek.completions("你好,你是谁?")
  10.                 .setOnMessage(event -> {
  11.                     // 接受和处理 SSE 事件
  12.                     try {
  13.                         // 获取消息数据,并反序列化为 DeepSeekResult 类
  14.                         DeepSeekResult result = event.value(DeepSeekResult.class);
  15.                         // 打印 DeepSeekResult 对象中的消息内容
  16.                         System.out.print(result.content());
  17.                     } catch (Exception e) {
  18.                     }
  19.                 })
  20.                 .listen(SSELinesMode.SINGLE_LINE); // 监听 SSE,并设置为单行消息模式
  21.     }
  22.     public static void main(String[] args) {
  23.         try {
  24.             SpringApplication.run(DeepSeekExampleApplication.class, args);
  25.         } catch (Throwable th) {
  26.             th.printStackTrace();
  27.         }
  28.     }
  29. }
复制代码
6.gif
其中,DeepSeekResult 是根据返回的消息格式定义的数据类,具体代码如下
  1. @Data
  2. public class DeepSeekResult {
  3.     private String id;
  4.     private String object;
  5.     private Integer created;
  6.     private String model;
  7.     @JSONField(name = "system_fingerprint")
  8.     private String systemFingerprint;
  9.     private List<JSONObject> choices;
  10.     // 获取消息中的 choices[0].delta.content
  11.     public String content() {
  12.         List<JSONObject> choices = getChoices();
  13.         if (CollectionUtil.isNotEmpty(choices)) {
  14.             JSONObject chooseJson = choices.get(0);
  15.             DeepSeekResultChoice choice = chooseJson.toJavaObject(DeepSeekResultChoice.class);
  16.             return choice.getDelta().getContent();
  17.         }
  18.         return "";
  19.     }
  20. }
复制代码
7.gif
其他的数据类包括 DeepSeekResultChoice 类也都类似。如果要看具体代码,在文章末尾会提供代码仓库地址。
六. 应答测试

调用方法写完之后,我们就可以跑一下代码看看了,点击 Run 之后可以看到控制台日志会打印以下内容
8.png

​日志上半部分POST https://api.deepseek.com/chat/completions HTTPS [SSE]这类信息为 Forest 的请求日志,会告诉您发出去的 HTTP 请求信息中有些什么数据和参数。
而下半部分 “您好!我是由中国的深度求索(DeepSeek)公司开发的智能助手DeepSeek-R1...” 自然就是 DeepSeek 的回答了。
七. 思维链

以上的代码案例,只会返回 DeepSeek 的回答内容,不包含他的思考过程,拿怕模型是DeepSeek-R1也一样。如果要打印出思维链,就要修改一下代码
首先要修改 DeepSeekResult 类中的 content() 方法
  1. @Data
  2. public class DeepSeekResult {
  3.     private String id;
  4.     private String object;
  5.     private Integer created;
  6.     private String model;
  7.     @JSONField(name = "system_fingerprint")
  8.     private String systemFingerprint;
  9.     private List<JSONObject> choices;
  10.     // 获取消息中的 choices[0].delta.reasoning_content
  11.     // 或 choices[0].delta.content
  12.     // 是否为思维内容,通过 DeepSeekContent.isReasoning 来标识
  13.     public DeepSeekContent content() {
  14.         List<JSONObject> choices = getChoices();
  15.         if (CollectionUtil.isNotEmpty(choices)) {
  16.             JSONObject chooseJson = choices.get(0);
  17.             DeepSeekResultChoice choice = chooseJson.toJavaObject(DeepSeekResultChoice.class);
  18.             String reasoningContent = choice.getDelta().getReasoningContent();
  19.             // 判断是否存在 reasoningContent,存在就是思维链内容,否则就是存粹的回答内容
  20.             if (StringUtils.isNotEmpty(reasoningContent)) {
  21.                 return new DeepSeekContent(true, reasoningContent);
  22.             }
  23.             return new DeepSeekContent(false, choice.getDelta().getContent());
  24.         }
  25.         return new DeepSeekContent();
  26.     }
  27. }
复制代码
9.gif
添加 DeepSeekContent 类
  1. @Data
  2. public class DeepSeekContent {
  3.     // 是否为思考过程内容
  4.     private boolean reasoning = false;
  5.     // DeepSeek 回答的具体内容
  6.     private String content = "";
  7.     public DeepSeekContent() {
  8.     }
  9.     public DeepSeekContent(boolean reasoning, String content) {
  10.         this.reasoning = reasoning;
  11.         this.content = content;
  12.     }
  13. }
复制代码
11.gif
最后,修改接口的调用部分
  1. @SpringBootApplication
  2. public class DeepSeekExampleApplication implements CommandLineRunner {
  3.     // DeepSeek 声名式接口
  4.     @Resource
  5.     private DeepSeek deepSeek;
  6.     @Override
  7.     public void run(String... args) {
  8.         // 标志位:是否为第一次接收到到思维链内容
  9.         AtomicBoolean isFirstReasoning = new AtomicBoolean(false);
  10.         // 调用声明式接口方法
  11.         deepSeek.completions("1+1等于几?")
  12.                 .setOnMessage(event -> {
  13.                     try {
  14.                         DeepSeekResult result = event.value(DeepSeekResult.class);
  15.                         DeepSeekContent content = result.content();
  16.                         // 通过 CAS 判断是否第一次接收到到思维链内容
  17.                         // 如果是,则打印出<思维链>标签
  18.                         if (content.isReasoning() && isFirstReasoning.compareAndSet(false, true)) {
  19.                             System.out.println("<思维链>");
  20.                             System.out.print(content.getContent());
  21.                         } else if (!content.isReasoning() && isFirstReasoning.compareAndSet(true, false)) {
  22.                             // 当 isFirstReasoning 由 true 转为 false
  23.                             // 则表明消息从思维链内容转向正式回答内容
  24.                             System.out.print(content.getContent());
  25.                             System.out.println("\n</思维链>\n");
  26.                         } else {
  27.                             // 打印正常的思维链或正式回答内容
  28.                             System.out.print(Opt.ofBlankAble(content.getContent()).orElse(""));
  29.                         }
  30.                     } catch (Exception e) {
  31.                     }
  32.                 })
  33.                 .listen(SSELinesMode.SINGLE_LINE);
  34.     }
  35.     public static void main(String[] args) {
  36.         try {
  37.             SpringApplication.run(DeepSeekExampleApplication.class, args);
  38.         } catch (Throwable th) {
  39.             th.printStackTrace();
  40.         }
  41.     }
  42. }
复制代码
13.gif
八. 思维链消息测试

接下来就可以运行程序测试了,看看日志中是否包含了思维链的过程
12.png

 
从日志中可以看出,程序正常运行了,其中被包裹在和标签中间的部分就是 DeepSeek 告诉我们的思维过程。 而在结束标签之后的文字就是他的正式回答内容。
九. 错误处理

本文案例调用的是 DeepSeek 官方的 API。由于众所周知的原因,调用接口时极有可能发生401等网络错误。
遇到这种请求,加一个拦截器就完事了
  1. // Forest 的 SSE 请求拦截器
  2. public class DeepSeekInterceptor implements SSEInterceptor {
  3.     // 接受到请求响应时会自动调用该方法
  4.     @Override
  5.     public ResponseResult onResponse(ForestRequest request, ForestResponse response) {
  6.         // 判断请求是否发生错误,如 401、404 等等
  7.         if (response.isError()) {
  8.             // 如有错,就打印“服务端繁忙,请稍后再试”
  9.             System.out.println("服务端繁忙,请稍后再试");
  10.             return success();
  11.         }
  12.         return proceed();
  13.     }
  14. }
复制代码
14.gif
然后,将拦截器绑定到接口上
  1. // 为整个接口绑定拦截器@BaseRequest(interceptor = DeepSeekInterceptor.class)public interface DeepSeek {
  2.    
  3.     @Post(
  4.             url = "https://api.deepseek.com/chat/completions",
  5.             contentType = "application/json",
  6.             headers = "Authorization: Bearer {apiKey}",
  7.             data = "{"messages":[{"content":"{content}","role":"user"}],"model":"{model}","stream":true}")
  8.     ForestSSE completions(@Var("content") String content);
  9. }
复制代码
十. 总结

可以看到,通过 Forest 这种声名式的形式来对接 DeepSeek API,相比于 OkHttp 和 HttpClient 有很多明显的好处。除了代码简洁,容易实现之外,更重要的是声名式代码天然更容易解耦。文本代码很自然的就实现了在参数配置、HTTP请求参数、以及接口调用的业务逻辑之间实现了代码解耦。如果要修改 API Key 或者模型,直接该配置文件就行。如果要修改 HTTP 的 URL 或参数,可以直接改声名式接口,而不会影响到调用接口的业务代码。而且可以很自然地将 DeepSeek API 的 HTTP 代码统一放到一个接口类中,方便管理,而且请求中的 URL、请求头、请求体参数都都一目了然。
代码仓库地址:forest: 声明式HTTP客户端API框架,让Java发送HTTP/HTTPS请求不再难。它比OkHttp和HttpClient更高层,是封装调用第三方restful api client接口的好帮手,是retrofit和feign之外另一个选择。通过在接口上声明注解的方式配置HTTP请求接口 - Gitee.com

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册