后端服务怎么通知前端?
假如说有这样的一个场景,下单,因为qps太高需要做异步的处理,异步处理完成后,需要通知前端的用户下单成功,那么这个通知要怎么实现呢?
- WebSocket 实时推送:前端在提交订单后,建立 WebSocket 连接(携带 order_id)。服务端通过 WebSocket 主动推送最终状态。
- 前端轮询:前端每隔1s轮询一下订单状态,看是否下单成功。
- SSE(Server-Sent Events):前端通过 EventSource 发起一个 HTTP 长连接请求,订阅后端推送过来的变化,需要由后端主动去推送结果。这种比比 WebSocket 更轻量。
- 异步查询:由前端自行通过查询接口展示结果。
webSocket实现实例:
SpringBoot:
@ServerEndpoint("/chat/{userId}")
public class ChatEndpoint {
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
// 新连接建立
}
@OnMessage
public void onMessage(String message, Session session) {
// 处理客户端消息
}
@OnClose
public void onClose(Session session) {
// 连接关闭
}
}
前端代码示例:
const socket = new WebSocket("wss://example.com/chat/user123");
// 监听消息
socket.onmessage = (event) => {
console.log("收到消息:", event.data);
};
// 发送消息
socket.send("Hello Server!");
SSE的示例:
前端代码示例:
const eventSource = new EventSource("/updates");
eventSource.onmessage = (event) => {
console.log("收到数据:", event.data);
};
eventSource.addEventListener("priceUpdate", (event) => {
console.log("自定义事件:", event.data);
});
SpringBoot:
@GetMapping(path = "/updates", produces = "text/event-stream")
public SseEmitter streamUpdates() {
SseEmitter emitter = new SseEmitter();
// 模拟定时推送
executor.scheduleAtFixedRate(() -> {
try {
emitter.send(SseEmitter.event()
.data(new StockPrice("AAPL", 150))
.id("1"));
} catch (IOException e) {
emitter.completeWithError(e);
}
}, 0, 1, TimeUnit.SECONDS);
return emitter;
}