Bootstrap

通过okhttp调用SSE流式接口,并将消息返回给客户端_okhttp sse

        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.78</version>
    </dependency>

#### 2. controller



package com.demo.controller;
import com.alibaba.fastjson.JSON;
import com.demo.listener.SSEListener;
import com.demo.params.req.ChatGlmDto;
import com.demo.utils.ApiTokenUtil;
import com.demo.utils.ExecuteSSEUtil;
import lombok.extern.slf4j.Slf4j;
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;
impor

;