在Spring Boot中,可以通过注入HttpServletResponse对象来获取。具体步骤如下:
-
在EventSourceListener类中定义一个HttpServletResponse类型的成员变量response,并添加一个构造函数,将response作为参数传入。
-
在onEvent方法中,通过response.getWriter()方法获取PrintWriter对象,然后使用该对象向客户端发送数据
以下是示例代码:
@Component
public class MyEventSourceListener implements EventSourceListener {
private HttpServletResponse response;
public MyEventSourceListener(HttpServletResponse response) {
this.response = response;
}
@Override
public void onOpen() throws IOException {
// 设置响应头
response.setContentType("text/event-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Connection", "keep-alive");
}
@Override
public void onEvent(String event, String id, String data) throws IOException {
PrintWriter writer = response.getWriter();
writer.write("event: " + event + "\n");
writer.write("id: " + id + "\n");
writer.write("data: " + data + "\n\n");
writer.flush();
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
try {
response.getWriter().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}