zxc 发表于 2025-2-13 10:20:50

干货:DeepSeek+SpringAI实现流式对话!


前一篇文章我们实现了《SpringAI集成满血版DeepSeek》,但是大模型的响应速度通常是很慢的,为了避免用户用户能够耐心等待输出的结果,我们通常会使用流式输出一点点将结果输出给用户。
那么问题来了,想要实现流式结果输出,后端和前端要如何配合?后端要使用什么技术实现流式输出呢?接下来本文给出具体的实现代码,先看最终实现效果:

解决方案

在 Spring Boot 中实现流式输出可以使用 Sse(Server-Sent Events,服务器发送事件)技术来实现,它是一种服务器推送技术,适合单向实时数据流,我们使用 Spring MVC(基于 Servlet)中的 SseEmitter 对象来实现流式输出。
具体实现如下。
1.后端代码

Spring Boot 程序使用 SseEmitter 对象提供的 send 方法发送数据,具体实现代码如下:
import org.springframework.http.MediaType;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;@RestControllerpublic class StreamController {    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)    public SseEmitter streamData() {      // 创建 SSE 发射器,设置超时时间(例如 1 分钟)      SseEmitter emitter = new SseEmitter(60_000L);      // 创建新线程,防止主程序阻塞      new Thread(() -> {            try {                for (int i = 1; i{            try {                String content = response.getResult().getOutput().getContent();                System.out.print(content);                // 发送 SSE 事件                emitter.send(SseEmitter.event()                           .data(content)                           .id(String.valueOf(System.currentTimeMillis()))                           .build());            } catch (Exception e) {                emitter.completeWithError(e);            }      },                                           error -> { // 异常处理                                             emitter.completeWithError(error);                                           },                                           () -> { // 完成处理                                             emitter.complete();                                           }                                          );      // 处理客户端断开连接      emitter.onCompletion(() -> {            // 可在此处释放资源            System.out.println("SSE connection completed");      });      emitter.onTimeout(() -> {            emitter.complete();            System.out.println("SSE connection timed out");      });      return emitter;    }}

[*]1.
[*]2.
[*]3.
[*]4.
[*]5.
[*]6.
[*]7.
[*]8.
[*]9.
[*]10.
[*]11.
[*]12.
[*]13.
[*]14.
[*]15.
[*]16.
[*]17.
[*]18.
[*]19.
[*]20.
[*]21.
[*]22.
[*]23.
[*]24.
[*]25.
[*]26.
[*]27.
[*]28.
[*]29.
[*]30.
[*]31.
[*]32.
[*]33.
[*]34.
[*]35.
[*]36.
[*]37.
[*]38.
[*]39.
[*]40.
[*]41.
[*]42.
[*]43.
[*]44.
[*]45.
[*]46.
[*]47.
[*]48.
[*]49.
[*]50.
[*]51.
[*]52.
[*]53.
[*]54.
[*]55.
[*]56.
[*]57.
[*]58.
[*]59.
[*]60.
[*]61.
[*]62.
[*]63.
[*]64.





前端核心 JS 代码如下:
$('#send-button').click(function () {const message = $('#chat-input').val();const eventSource = new EventSource(`/ai/generateStream?message=` + message);// 构建动态结果var chatMessages = $('#chat-messages');var newMessage = $('
');newMessage.append('');newMessage.append(`${message}`);chatMessages.prepend(newMessage);var botMessage = $('
');botMessage.append('');// 流式输出eventSource.onmessage = function (event) {    botMessage.append(`${event.data}`);};chatMessages.prepend(botMessage);$('#chat-input').val('');eventSource.onerror = function (err) {    console.error("EventSource failed:", err);    eventSource.close();};});

[*]1.
[*]2.
[*]3.
[*]4.
[*]5.
[*]6.
[*]7.
[*]8.
[*]9.
[*]10.
[*]11.
[*]12.
[*]13.
[*]14.
[*]15.
[*]16.
[*]17.
[*]18.
[*]19.
[*]20.
[*]21.
[*]22.





以上代码中的“$”代表的是 jQuery。
页: [1]
查看完整版本: 干货:DeepSeek+SpringAI实现流式对话!