jeecgboot 使用SseEmitter
时间: 2025-01-22 19:13:21 浏览: 63
### JeecgBoot 中使用 `SseEmitter` 实现 SSE 服务器发送事件
#### 创建控制器类
为了在 JeecgBoot 中实现 SSE (Server-Sent Events),可以创建一个名为 `SSEController` 的控制器来处理 `/events` 路径下的 GET 请求。此路径将负责建立与客户端之间的持续连接并发送更新。
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@RequestMapping("/api/sse")
public class SSEController {
@GetMapping(value = "/events", produces = "text/event-stream")
public SseEmitter handle() throws InterruptedException {
final var emitter = new SseEmitter();
// 设置超时时间,防止长时间无响应被浏览器断开,默认30秒
emitter.setTimeout(0L);
// 发送数据给前端
sendEvent(emitter, "Connecting...");
// 模拟异步任务或定时器触发的数据推送逻辑
for(int i=1; i<=5 ;i++) {
Thread.sleep(2000); // 延迟两秒钟模拟延迟加载新消息
String data = "Message "+i+" at time:"+System.currentTimeMillis()/1000;
sendEvent(emitter,data);
}
return emitter;
}
private void sendEvent(SseEmitter emitter, Object data){
try{
emitter.send(data);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
```
上述代码展示了如何通过 Java Spring MVC 注解配置 RESTful API 来支持 Server Sent Event 功能[^1]。请注意,在实际应用环境中应当考虑异常情况以及资源释放等问题。
#### 配置文件调整
确保项目的 Web 安全设置允许跨域资源共享(CORS), 如果前后端分离部署的话:
```yaml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
security:
cors:
enabled: true
cors:
allowed-origins: "*"
allowed-methods: "*"
allowed-headers: "*"
exposed-headers: "X-AUTH-TOKEN"
allow-credentials: true
max-age: 3600
```
以上 YAML 片段应放置于 application.yml 文件内以启用 CORS 政策,从而让不同源的页面能够接收到来自服务器的消息通知[^2]。
阅读全文
相关推荐

















