springboot结合deepseek流式输出
时间: 2025-03-25 19:17:19 浏览: 71
### Spring Boot 中集成 DeepSeek 实现流式输出
要在 Spring Boot 应用程序中实现与 DeepSeek 的集成并支持流式输出功能,可以按照以下方法设计架构和编写代码。
#### 1. 添加依赖项
首先,在 `pom.xml` 或 `build.gradle` 文件中引入必要的依赖项。以下是 Maven 示例:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.0</version>
</dependency>
```
上述配置包含了 WebFlux 和 OkHttp 客户端库,用于处理异步请求以及流式数据传输[^1]。
---
#### 2. 创建 Controller 层
定义一个 REST 控制器来接收客户端请求并将结果作为流返回给前端。
```java
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
@RestController
@RequestMapping("/deepseek")
public class DeepSeekController {
private final DeepSeekService deepSeekService;
public DeepSeekController(DeepSeekService deepSeekService) {
this.deepSeekService = deepSeekService;
}
@GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getStreamResponse(@RequestParam String prompt) {
return deepSeekService.generateStream(prompt);
}
}
```
此控制器通过 `/deepseek/stream?prompt=...` 接口接受输入提示,并调用服务层生成响应流。
---
#### 3. 设计 Service 层逻辑
在服务类中封装实际的 HTTP 请求发送过程,利用 OkHttp 来获取来自 DeepSeek API 的实时更新内容。
```java
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
@Service
public class DeepSeekService {
private static final OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(0, TimeUnit.SECONDS) // 设置无超时时间以便持续监听
.build();
public Flux<String> generateStream(String prompt) {
RequestBody body = RequestBody.create(
"{ \"text\": \"" + prompt + "\", \"use_cache\": false }",
MediaType.get("application/json; charset=utf-8"));
Request request = new Request.Builder()
.url("https://api.deepseek.com/v1/completions") // 替换为目标 URL
.post(body)
.addHeader("Authorization", "Bearer YOUR_API_KEY") // 插入您的密钥
.build();
return Flux.create(sink -> {
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
ResponseBody responseBody = response.body();
if (responseBody != null) {
BufferedReader reader = new BufferedReader(responseBody.charStream());
String line;
while ((line = reader.readLine()) != null && !sink.isCancelled()) {
sink.next(line); // 将每条消息推送到订阅者
}
}
} catch (Exception e) {
sink.error(e);
} finally {
sink.complete(); // 结束序列
}
});
}
}
```
这段代码实现了向 DeepSeek 发送 POST 请求的功能,并解析其 SSE(Server-Sent Events)格式的数据流[^2]。
---
#### 4. 前端测试工具推荐
为了验证后端接口是否正常工作,可借助 Postman 工具模拟 GET 请求访问该资源路径。另外也可以直接嵌套到 HTML 页面里使用 JavaScript 动态加载 SSE 数据。
示例 HTML 片段如下所示:
```html
<script type="text/javascript">
const eventSource = new EventSource('/deepseek/stream?prompt=hello');
eventSource.onmessage = function(event) {
console.log('New message:', JSON.parse(event.data));
};
</script>
```
以上脚本会不断打印服务器推送过来的新片段至浏览器控制台窗口内显示出来。
---
#### 总结
综上所述,本文介绍了如何基于 Spring Boot 构建一套能够对接 DeepSeek 平台完成自然语言交互任务的应用系统框架结构图解及其关键技术要点分析。
阅读全文
相关推荐


















