JAVA设计模式-监听者模式

什么是监听者模式

监听器模式是一种观察者模式的扩展,也被称为发布-订阅模式。在监听器模式中,存在两类角色:事件源(Event Source)和监听器(Listener)。事件源负责产生事件,而监听器负责监听事件的发生并采取相应的行动。当事件源触发事件时,所有注册了对应类型监听器的对象都会得到通知,然后执行相应的操作。

应用背景

1.封装一个AI-GPT工具包,集成国内大模型,实现流式聊天

2.作为工具包不能依赖springboot-web,也就是不能把HttpServletResponse当做参数传递

方案

把监听者当做一个参数传入工具包,监听整个流的输出

调用方

复制代码
public Text2TextStreamObserver streamOutputResposeOberverBuild(ResponseBodyEmitter emitter,AiChatDto aiChatDto) {
        StringBuffer sb = new StringBuffer();
        return new Text2TextStreamObserver() {
            @Override
            public void onBegin() {
            }
            @Override
            public void onNext(String data) {
                try {
                    emitter.send(data);
                    sb.append(data);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            @Override
            public void onEnd() {
                try {
                    emitter.complete();
                    createLog(aiChatDto, sb.toString());
                    LOGGER.info("问题:{},答案:{}",JSONUtil.toJsonStr(aiChatDto),sb);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            @Override
            public void onFailure(Throwable throwable) {
                try {
                    emitter.completeWithError(throwable);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        };
    }

工具包

复制代码
public List<String> text2TextStream(MoonshotText2TextInput input, Text2TextStreamObserver streamObserver) {
        ArrayList dataList = new ArrayList();
        try {
            Request request = this.buildRequest(input, true);
            SSEListener sseListener = new SSEListener(dataList, streamObserver);
            ExecuteSSEUtil.executeSSE(request, sseListener, this.httpclient);
            return dataList;
        } catch (Exception var6) {
            throw new RuntimeException("流式请求异常:", var6);
        }
    }

SSEListener extends EventSourceListener
相关推荐
毕设源码-邱学长2 分钟前
【开题答辩全过程】以 基于SpringBoot的理工学院学术档案管理系统为例,包含答辩的问题和答案
java·spring boot·后端
神奇小梵2 分钟前
c语言易错知识点
c语言·开发语言
人机与认知实验室3 分钟前
<span class=“js_title_inner“>如何看待特斯拉第三代Optimus机器人?</span>
开发语言·javascript·机器人·ecmascript·unix
shejizuopin5 分钟前
基于SSM的高校旧书交易系统的设计与实现(毕业论文)
java·mysql·毕业设计·论文·ssm·毕业论文·高校旧书交易系统的设计与实现
Coding茶水间9 分钟前
基于深度学习的花朵识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
开发语言·人工智能·深度学习·yolo·目标检测·机器学习
修己xj11 分钟前
SpringBoot解析.mdb文件实战指南
java·spring boot·后端
咩图32 分钟前
Sketchup软件二次开发+Ruby+VisualStudioCode
java·前端·ruby
moxiaoran575332 分钟前
Go语言的文件操作
开发语言·后端·golang
我命由我1234535 分钟前
Android 开发问题:Duplicate class android.support.v4.app.INotificationSideChannel...
android·java·开发语言·java-ee·android studio·android-studio·android runtime
熬夜敲代码的小N41 分钟前
Unity大场景卡顿“急救包”:从诊断到落地的全栈优化方案
java·unity·游戏引擎