Spring Boot集成sse实现chatgpt流式交互
    		       		warning:
    		            这篇文章距离上次修改已过427天,其中的内容可能已经有所变动。
    		        
        		                
                
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 ChatGPTStreamController {
 
    @GetMapping(path = "/stream/chatgpt", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChatGPTMessages() {
        SseEmitter emitter = new SseEmitter();
 
        // 在新线程中处理发送消息的逻辑
        new Thread(() -> {
            try {
                // 模拟从ChatGPT接收消息的过程
                for (int i = 0; i < 10; i++) {
                    // 假设从ChatGPT获取到的响应
                    String message = "{\"message\":\"这是第" + i + "条消息\"}";
                    emitter.send(SseEmitter.event().data(message));
                    Thread.sleep(1000); // 每秒发送一次消息
                }
                emitter.complete(); // 流处理完毕后,关闭连接
            } catch (Exception e) {
                emitter.completeWithError(e); // 发送错误信息并关闭连接
            }
        }).start();
 
        return emitter;
    }
}这段代码展示了如何在Spring Boot应用中使用SseEmitter来实现一个简单的与ChatGPT的流式消息交互。它创建了一个新的线程来模拟从ChatGPT接收消息,并通过SseEmitter发送给客户端。当消息处理完毕或发生错误时,新线程会关闭SseEmitter,结束消息推送。
评论已关闭