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
相关推荐
Java 码农18 分钟前
Centos7 maven 安装
java·python·centos·maven
harmful_sheep26 分钟前
maven mvn 安装自定义 jar 包
java·maven·jar
Lucis__1 小时前
再探类&对象——C++入门进阶
开发语言·c++
007php0071 小时前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
JH30731 小时前
第七篇:Buffer Pool 与 InnoDB 其他组件的协作
java·数据库·mysql·oracle
lsx2024062 小时前
HTML 字符集
开发语言
很㗊2 小时前
C与C++---类型转换
c语言·开发语言
say_fall2 小时前
精通C语言(3. 自定义类型:联合体和枚举)
c语言·开发语言
郝学胜-神的一滴2 小时前
Effective Python 第43条:自定义容器类型为什么应该从 `collections.abc` 继承?
开发语言·python
jndingxin2 小时前
c++多线程(6)------ 条件变量
开发语言·c++