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
相关推荐
yugi9878382 分钟前
C# 串口下载烧写BIN文件工具
开发语言·c#
开心码农1号29 分钟前
Java rabbitMQ如何发送、消费消息、全套可靠方案
java·rabbitmq·java-rabbitmq
EAIReport31 分钟前
国外网站数据批量采集技术实现路径
开发语言·python
超绝振刀怪32 分钟前
【C++可变模板参数】
开发语言·c++·可变模板参数
蜡台38 分钟前
JetBrains IDEA 安装 卸载相关总结
java·ide·intellij-idea·注册码
WJLSH12338 分钟前
TomCat
java·tomcat
Freak嵌入式43 分钟前
MicroPython LVGL基础知识和概念:时序与动态效果
开发语言·python·github·php·gui·lvgl·micropython
戮戮1 小时前
Spring Cloud Gateway 零拷贝参数校验:一种高性能网关架构实践
java·网络·架构·gateway
2501_933329551 小时前
企业媒体发布与舆情管理实战:Infoseek舆情系统技术架构与落地解析
大数据·开发语言·人工智能·数据库开发