亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

基于SpringAI+DeepSeek實(shí)現(xiàn)流式對(duì)話功能

 更新時(shí)間:2025年02月13日 09:31:19   作者:Java中文社群  
一般來說大模型的響應(yīng)速度通常是很慢的,為了避免用戶用戶能夠耐心等待輸出的結(jié)果,我們通常會(huì)使用流式輸出一點(diǎn)點(diǎn)將結(jié)果輸出給用戶,那么問題來了,想要實(shí)現(xiàn)流式結(jié)果輸出,后端和前端要如何配合?下來本文給出具體的實(shí)現(xiàn)代碼,需要的朋友可以參考下

引言

前面一篇文章我們實(shí)現(xiàn)了《Spring AI內(nèi)置DeepSeek的詳細(xì)步驟》,但是大模型的響應(yīng)速度通常是很慢的,為了避免用戶用戶能夠耐心等待輸出的結(jié)果,我們通常會(huì)使用流式輸出一點(diǎn)點(diǎn)將結(jié)果輸出給用戶。

那么問題來了,想要實(shí)現(xiàn)流式結(jié)果輸出,后端和前端要如何配合?后端要使用什么技術(shù)實(shí)現(xiàn)流式輸出呢?接下來本文給出具體的實(shí)現(xiàn)代碼,先看最終實(shí)現(xiàn)效果:

解決方案

在 Spring Boot 中實(shí)現(xiàn)流式輸出可以使用 Sse(Server-Sent Events,服務(wù)器發(fā)送事件)技術(shù)來實(shí)現(xiàn),它是一種服務(wù)器推送技術(shù),適合單向?qū)崟r(shí)數(shù)據(jù)流,我們使用 Spring MVC(基于 Servlet)中的 SseEmitter 對(duì)象來實(shí)現(xiàn)流式輸出。

具體實(shí)現(xiàn)如下。

1.后端代碼

Spring Boot 程序使用 SseEmitter 對(duì)象提供的 send 方法發(fā)送數(shù)據(jù),具體實(shí)現(xiàn)代碼如下:

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;

@RestController
public class StreamController {

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamData() {
        // 創(chuàng)建 SSE 發(fā)射器,設(shè)置超時(shí)時(shí)間(例如 1 分鐘)
        SseEmitter emitter = new SseEmitter(60_000L);
        // 創(chuàng)建新線程,防止主程序阻塞
        new Thread(() -> {
            try {
                for (int i = 1; i <= 5; i++) {
                    Thread.sleep(1000); // 模擬延遲
                    // 發(fā)送數(shù)據(jù)
                    emitter.send("time=" + System.currentTimeMillis());
                }
                // 發(fā)送完畢
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}

2.前端代碼

前端接受數(shù)據(jù)流也比較簡單,不需要在使用傳統(tǒng) Ajax 技術(shù)了,只需要?jiǎng)?chuàng)建一個(gè) EventSource 對(duì)象,監(jiān)聽后端 SSE 接口,然后將接收到的數(shù)據(jù)流展示出來即可,如下代碼所示:

<!DOCTYPE html>
<html>
  <head>
    <title>流式輸出示例</title>
  </head>
  <body>
    <h2>流式數(shù)據(jù)接收演示</h2>
    <button onclick="startStream()">開始接收數(shù)據(jù)</button>
    <div id="output" style="margin-top: 20px; border: 1px solid #ccc; padding: 10px;"></div>

    <script>
      function startStream() {
        const output = document.getElementById('output');
        output.innerHTML = ''; // 清空之前的內(nèi)容

        const eventSource = new EventSource('/stream');

        eventSource.onmessage = function(e) {
          const newElement = document.createElement('div');
          newElement.textContent = "print -> " + e.data;
          output.appendChild(newElement);
        };

        eventSource.onerror = function(e) {
          console.error('EventSource 錯(cuò)誤:', e);
          eventSource.close();
          const newElement = document.createElement('div');
          newElement.textContent = "連接關(guān)閉";
          output.appendChild(newElement);
        };
      }
    </script>
  </body>
</html>

3.運(yùn)行項(xiàng)目

運(yùn)行項(xiàng)目測試結(jié)果:

  • 啟動(dòng) Spring Boot 項(xiàng)目。
  • 在瀏覽器中訪問地址 http://localhost:8080/index.html,即可看到流式輸出的內(nèi)容逐漸顯示在頁面上。

4.最終版:流式輸出

后端代碼如下:

import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;

@RestController
public class ChatController {
    private final OpenAiChatModel chatModel;

    @Autowired
    public ChatController(OpenAiChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @GetMapping("/ai/generate")
    public Map generate(@RequestParam(value = "message", defaultValue = "你是誰?") String message) {
        return Map.of("generation", this.chatModel.call(message));
    }

    @GetMapping("/ai/generateStream")
    public SseEmitter streamChat(@RequestParam String message) {
        // 創(chuàng)建 SSE 發(fā)射器,設(shè)置超時(shí)時(shí)間(例如 1 分鐘)
        SseEmitter emitter = new SseEmitter(60_000L);
        // 創(chuàng)建 Prompt 對(duì)象
        Prompt prompt = new Prompt(new UserMessage(message));
        // 訂閱流式響應(yīng)
        chatModel.stream(prompt).subscribe(response -> {
            try {
                String content = response.getResult().getOutput().getContent();
                System.out.print(content);
                // 發(fā)送 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;
    }
}

前端核心 JS 代碼如下:

$('#send-button').click(function () {
  const message = $('#chat-input').val();
  const eventSource = new EventSource(`/ai/generateStream?message=` + message);
  // 構(gòu)建動(dòng)態(tài)結(jié)果
  var chatMessages = $('#chat-messages');
  var newMessage = $('<div class="message user"></div>');
  newMessage.append('<img class="avatar" src="/imgs/user.png" alt="用戶頭像">');
  newMessage.append(`<span class="nickname">${message}</span>`);
  chatMessages.prepend(newMessage);
  var botMessage = $('<div class="message bot"></div>');
  botMessage.append('<img class="avatar" src="/imgs/robot.png" alt="助手頭像">');
  // 流式輸出
  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();
  };
});

以上代碼中的“$”代表的是 jQuery。

到此這篇關(guān)于基于Spring AI+DeepSeek實(shí)現(xiàn)流式對(duì)話功能的文章就介紹到這了,更多相關(guān)Spring AI DeepSeek流式對(duì)話內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java BeanUtils工具類常用方法講解

    Java BeanUtils工具類常用方法講解

    這篇文章主要介紹了Java BeanUtils工具類常用方法講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 解析SpringBoot @EnableAutoConfiguration的使用

    解析SpringBoot @EnableAutoConfiguration的使用

    這篇文章主要介紹了解析SpringBoot @EnableAutoConfiguration的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-09-09
  • springboot+zookeeper實(shí)現(xiàn)分布式鎖的示例代碼

    springboot+zookeeper實(shí)現(xiàn)分布式鎖的示例代碼

    本文主要介紹了springboot+zookeeper實(shí)現(xiàn)分布式鎖的示例代碼,文中根據(jù)實(shí)例編碼詳細(xì)介紹的十分詳盡,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • Java使用DFA算法實(shí)現(xiàn)過濾多家公司自定義敏感字功能詳解

    Java使用DFA算法實(shí)現(xiàn)過濾多家公司自定義敏感字功能詳解

    這篇文章主要介紹了Java使用DFA算法實(shí)現(xiàn)過濾多家公司自定義敏感字功能,結(jié)合實(shí)例形式分析了DFA算法的實(shí)現(xiàn)原理及過濾敏感字的相關(guān)操作技巧,需要的朋友可以參考下
    2017-08-08
  • 超細(xì)講解Java調(diào)用python文件的幾種方式

    超細(xì)講解Java調(diào)用python文件的幾種方式

    有時(shí)候我們?cè)趯慾ava的時(shí)候需要調(diào)用python文件,下面這篇文章主要給大家介紹了關(guān)于Java調(diào)用python文件的幾種方式,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-12-12
  • springboot配置多數(shù)據(jù)源的一款框架(dynamic-datasource-spring-boot-starter)

    springboot配置多數(shù)據(jù)源的一款框架(dynamic-datasource-spring-boot-starter

    dynamic-datasource-spring-boot-starter 是一個(gè)基于 springboot 的快速集成多數(shù)據(jù)源的啟動(dòng)器,今天通過本文給大家分享這款框架配置springboot多數(shù)據(jù)源的方法,一起看看吧
    2021-09-09
  • Java基于Socket的文件傳輸實(shí)現(xiàn)方法

    Java基于Socket的文件傳輸實(shí)現(xiàn)方法

    這篇文章主要介紹了Java基于Socket的文件傳輸實(shí)現(xiàn)方法,結(jié)合實(shí)例分析了Java使用Socket實(shí)現(xiàn)文件傳輸?shù)慕⑦B接、發(fā)送與接收消息、文件傳輸?shù)认嚓P(guān)技巧,需要的朋友可以參考下
    2015-12-12
  • SpringBoot中對(duì)SpringMVC的自動(dòng)配置詳解

    SpringBoot中對(duì)SpringMVC的自動(dòng)配置詳解

    這篇文章主要介紹了SpringBoot中的SpringMVC自動(dòng)配置詳解,Spring MVC自動(dòng)配置是Spring Boot提供的一種特性,它可以自動(dòng)配置Spring MVC的相關(guān)組件,簡化了開發(fā)人員的配置工作,需要的朋友可以參考下
    2023-10-10
  • Feign 使用HttpClient和OkHttp方式

    Feign 使用HttpClient和OkHttp方式

    這篇文章主要介紹了Feign 使用HttpClient和OkHttp方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • SpringBoot中的@EnableConfigurationProperties注解詳細(xì)解析

    SpringBoot中的@EnableConfigurationProperties注解詳細(xì)解析

    這篇文章主要介紹了SpringBoot中的@EnableConfigurationProperties注解詳細(xì)解析,如果一個(gè)配置類只配置@ConfigurationProperties注解,而沒有使用@Component或者實(shí)現(xiàn)了@Component的其他注解,那么在IOC容器中是獲取不到properties 配置文件轉(zhuǎn)化的bean,需要的朋友可以參考下
    2024-01-01

最新評(píng)論