import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
@RestController
@Slf4j
public class APITestController {
private static final String API\_KEY = "xxxx";
private static final String URL = "xxx";
@PostMapping(value = "/sse-invoke", produces = "text/event-stream;charset=UTF-8")
public void sse(@RequestBody ChatGlmDto chatGlmDto, HttpServletResponse rp) {
try {
String token = ApiTokenUtil.generateClientToken(API\_KEY);
SSEListener sseListener = new SSEListener(chatGlmDto, rp);
ExecuteSSEUtil.executeSSE(URL, token, sseListener, JSON.toJSONString(chatGlmDto));
} catch (Exception e) {
log.error("请求SSE错误处理", e);
}
}
}
#### 3. 监听器
监听器里的事件可以自己定义,然后自己去实现自己相关的业务逻辑,onEvent主要用来接收消息
package com.demo.listener;
import com.alibaba.fastjson.JSON;
import com.demo.params.req.ChatGlmDto;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.CountDownLatch;
@Slf4j
@Data
public class SSEListener extends EventSourceListener {
private CountDownLatch countDownLatch = new CountDownLatch(1);
private ChatGlmDto chatGlmDto;
private HttpServletResponse rp;
private StringBuffer output = new StringBuffer();
public SSEListener(ChatGlmDto chatGlmDto, HttpServletResponse response) {
this.chatGlmDto = chatGlmDto;
this.rp = response;
}
/\*\*
* {@inheritDoc}
* 建立sse连接
*/
@Override
public void onOpen(final EventSource eventSource, final Response
response) {<