博客主页: 南来_北往
系列专栏:Spring Boot实战
SSE可以指代两种不同的概念:一是指“服务器发送事件”(Server-Sent Events),另一种是指英特尔的“因特网数据流单指令序列扩展”(Streaming SIMD Extensions)。下面将逐一解释这两种概念:
综上所述,SSE既可以指服务器向客户端实时推送数据的“服务器发送事件”技术,也可以指英特尔为提升多媒体处理性能而开发的“因特网数据流单指令序列扩展”指令集。这两种技术虽然应用领域不同,但都极大地提升了相应领域的效率和体验。
SSE(Server-Sent Events)和WebSocket都是实现实时通信的重要技术,但它们在设计理念、实现方式和适用场景上存在显著差异。
SSE是一种基于HTTP协议的单向通信技术,允许服务器主动向客户端推送数据。相比之下,WebSocket提供了一个全双工通信通道,支持客户端和服务器之间的双向数据交换。下面从多个角度详细对比这两种技术:
综上所述,如果应用只需服务器单向推送数据且要求简单实现,SSE是理想选择;而对于需要高度互动、双向数据传输的场景,WebSocket则更具优势。在选择实时通信技术时,应根据具体需求来决定采用SSE还是WebSocket,从而更好地满足项目需求和提升用户体验。
实现chatgpt流式交互
springboot-demo com.et 1.0-SNAPSHOT 4.0.0 sse 8 8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-autoconfigure org.springframework.boot spring-boot-starter-test test cn.hutool hutool-all 5.8.9 org.projectlombok lombok
package com.et.sse.controller; import cn.hutool.core.util.IdUtil; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import java.io.IOException; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Controller @RequestMapping("/chat") public class ChatController { Map msgMap = new ConcurrentHashMap<>(); /** * send meaaage * @param msg * @return */ @ResponseBody @PostMapping("/sendMsg") public String sendMsg(String msg) { String msgId = IdUtil.simpleUUID(); msgMap.put(msgId, msg); return msgId; } /** * conversation * @param msgId mapper with sendmsg * @return */ @GetMapping(value = "/conversation/{msgId}", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter conversation(@PathVariable("msgId") String msgId) { SseEmitter emitter = new SseEmitter(); String msg = msgMap.remove(msgId); //mock chatgpt response new Thread(() -> { try { for (int i = 0; i < 10; i++) { ChatMessage chatMessage = new ChatMessage("test", new String(i+"")); emitter.send(chatMessage); Thread.sleep(1000); } emitter.send(SseEmitter.event().name("stop").data("")); emitter.complete(); // close connection } catch (IOException | InterruptedException e) { emitter.completeWithError(e); // error finish } }).start(); return emitter; } }
ChatGpt test ChatGpt Test
send
以上只是一些关键代码,具体根据自己项目进行编码