
去掉setInterval轮询,使用EventSource+SSE
去掉setInterval轮询,使用EventSource+SSE。核心 代码不多。
springboot创建SSE API
@RestController @RequestMapping("/h5/sse") @Log4j2 public class SseController { @Autowired SseService sseService; @GetMapping("/order/{orderId}") public SseEmitter handleSse(@PathVariable Long orderId) { return sseService.subscribeOrderStatus(orderId); } }
创建SseService
public interface SseService { SseEmitter subscribeOrderStatus(Long orderId); void pushOrderStatusUpdate(Long orderId, Integer status); void removeOrderEmitter(Long orderId); }
SSEServiceImpl:
@Service @Log4j2 public class SseServiceImpl implements SseService { private final ConcurrentHashMap<Long, SseEmitter> orderEmitters = new ConcurrentHashMap<>(); @Override public SseEmitter subscribeOrderStatus(Long orderId) { SseEmitter emitter = new SseEmitter(5 * 60 * 1000L); emitter.onTimeout(() -> orderEmitters.remove(orderId)); emitter.onCompletion(() -> orderEmitters.remove(orderId)); orderEmitters.put(orderId, emitter); return emitter; } // 推送订单状态更新 @Override public void pushOrderStatusUpdate(Long orderId, Integer status) { SseEmitter emitter = orderEmitters.get(orderId); if (emitter != null) { try { Map<String, Object> data=new HashMap<>(); data.put("orderId", orderId); data.put("status", status); emitter.send(JSONUtil.toString(data), MediaType.TEXT_EVENT_STREAM); } catch (Exception e) { emitter.completeWithError(e); } } } @Override public void removeOrderEmitter(Long orderId) { orderEmitters.remove(orderId); } }
前端:
安装 event-source-polyfill (支持配置 headers)
function sse(id) { const eventSource = new EventSourcePolyfill(baseApiUrl + "/sse/order/" + id, { heartbeatTimeout: 5 * 60 * 1000, // 配置请求超时时间 headers: { 'Authorization': 'bearer ' + getToken(), } }); eventSource.onmessage = function (event) { event = JSON.parse(event.data); console.log(event); if (event.status != reservation.value.status) { loadReservation(); } }; eventSource.onerror = function () { console.error("EventSource failed."); }; }
============ 欢迎各位老板打赏~ ===========


与本文相关的文章
- · mybatis plus新版代码生成器 去掉 i 前缀
- · Java基础问题13个,你都会哪些?
- · 不重新打包项目并替换部分jar包
- · 接收企微事件回调 Content type ‘text/xml;charset=UTF-8’ not supported
- · springboot使用lock4j实现并发控制
- · springboot全局增加sentinel
- · linux快速搭建轻量级efk日志系统
- · Springboot整合Swagger常用注解
- · swagger隐藏authentication参数
- · Spring Security 中的自定义PreAuthorize 注解
- · Expected one result (or null) to be returned by selectOne(), but found: 2
- · JACKSON和FASTJSON处理返回JSON数据中为NULL字段不显示