WebSocket 实战:用 Spring Boot 实现实时消息推送

WebSocket in Practice — Real-Time Push Notifications with Spring Boot

| iDev Team | 2026-08-13T09:46:30

HTTP 轮询太浪费?SSE 单向不够用?WebSocket 是实时双向通信的最优解。本文教你用 Spring Boot 从零实现。

HTTP polling too wasteful? SSE too one-directional? WebSocket is the optimal solution for real-time bidirectional communication. Build it from scratch with Spring Boot.

为什么需要 WebSocket传统 HTTP 是请求-响应模式,服务端不能主动推送。如果你需要实时功能(聊天、通知、协同编辑、实时看板),有三个选择:轮询:前端定时请求,浪费带宽和服务器资源SSE:服务端单向推送,不支持双向通信WebSocket:全双工、低延迟、省资源Spring Boot 集成方案Spring Boot 内置 WebSocket 支持。引入 spring-boot-starter-websocket,配置 WebSocket 端点,实现消息处理器。可以用原生 WebSocket API,也可以用 STOMP 协议(更高层的消息协议,支持主题订阅)。关键技术点连接管理用 ConcurrentHashMap 管理在线用户的 WebSocket Session。用户上线加入,下线移除。支持按用户 ID 单点推送,也支持广播。心跳检测WebSocket 连接可能因网络问题静默断开。配置 ping/pong 心跳机制,定时检测连接存活,及时清理死连接。断线重连前端检测到连接断开后自动重连,用指数退避策略(1s → 2s → 4s → 8s → 最大 30s),避免大量客户端同时重连冲击服务器。适用场景管理后台的实时通知(新订单、新工单)在线客服聊天多人协同编辑数据大屏实时刷新游戏或竞拍场景


Why WebSocketTraditional HTTP is request-response — servers can't proactively push data. For real-time features (chat, notifications, collaborative editing, live dashboards), there are three options:Polling: Frontend requests periodically — wastes bandwidth and server resourcesSSE: Server-side push only — no bidirectional communicationWebSocket: Full-duplex, low latency, resource efficientSpring Boot IntegrationSpring Boot has built-in WebSocket support. Add spring-boot-starter-websocket, configure WebSocket endpoints, implement message handlers. Use either raw WebSocket API or STOMP protocol (higher-level messaging with topic subscriptions).Key Technical PointsConnection ManagementUse ConcurrentHashMap to track online users' WebSocket sessions. Add on connect, remove on disconnect. Support targeted push by user ID and broadcast.Heartbeat DetectionWebSocket connections can silently drop due to network issues. Configure ping/pong heartbeat to periodically check connection health and clean up dead connections.ReconnectionFrontend auto-reconnects on disconnect using exponential backoff (1s → 2s → 4s → 8s → max 30s) to avoid thundering herd reconnection storms.Use CasesAdmin panel real-time notifications (new orders, new tickets)Live customer service chatCollaborative editingData dashboard live refreshGaming or auction scenarios

← Back to News