什么是监听者模式
监听器模式是一种观察者模式的扩展,也被称为发布-订阅模式。在监听器模式中,存在两类角色:事件源(Event Source)和监听器(Listener)。事件源负责产生事件,而监听器负责监听事件的发生并采取相应的行动。当事件源触发事件时,所有注册了对应类型监听器的对象都会得到通知,然后执行相应的操作。
应用背景
1.封装一个AI-GPT工具包,集成国内大模型,实现流式聊天
2.作为工具包不能依赖springboot-web,也就是不能把HttpServletResponse当做参数传递
方案
把监听者当做一个参数传入工具包,监听整个流的输出
调用方
public Text2TextStreamObserver streamOutputResposeOberverBuild(ResponseBodyEmitter emitter,AiChatDto aiChatDto) {StringBuffer sb = new StringBuffer();return new Text2TextStreamObserver() {@Overridepublic void onBegin() {}@Overridepublic void onNext(String data) {try {emitter.send(data);sb.append(data);} catch (IOException e) {throw new RuntimeException(e);}}@Overridepublic void onEnd() {try {emitter.complete();createLog(aiChatDto, sb.toString());LOGGER.info("问题:{},答案:{}",JSONUtil.toJsonStr(aiChatDto),sb);} catch (Exception e) {throw new RuntimeException(e);}}@Overridepublic 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