How to Integrate WebSocket + STOMP in Spring Boot for Scalable Real‑Time Messaging
This guide demonstrates how to integrate WebSocket and STOMP into a Spring Boot application, covering setup, core modules, code examples for broadcasting and targeted messages, and a cluster mode using Redis for distributed session forwarding.
Integration Example
The code has been used in production and can handle tens of thousands of daily active users.
Demo
GitHub repository: https://github.com/yangli-stu/quick-notify
Local Startup
After installing Redis, start the service directly without MySQL dependency: docker run -d --name redis -p 6379:6379 redis Open the browser to view: src/main/resources/stomp-websocket-sockjs.html Demo screenshot:
Project Overview
This project shows how to integrate WebSocket + STOMP in a Spring Boot application, achieving:
Real‑time message communication
Token‑based user authentication
Point‑to‑point message push
WebSocket session forwarding in a clustered environment
Applicable scenarios include social‑type notifications, real‑time status updates, and online customer service.
Core Module Structure
Path:
src/main/java/io/stu/notify/stomp ├── NotifyMessage.java // WebSocket message structure definition
├── NotifyType.java // Message type enum
├── StompWebSocketHandler.java // Message push manager
├── StompWebsocketConfig.java // STOMP/WebSocket configuration
└── StompWebsocketInterceptor.java // Authentication interceptorStompWebsocketConfig
Role: Configures WebSocket endpoints and message broker.
Explanation: Implements WebSocketMessageBrokerConfigurer interface.
StompWebsocketInterceptor
Role: Intercepts WebSocket connection requests for Token authentication.
Explanation: Implements ChannelInterceptor and binds user to session.
StompWebSocketHandler
Role: Manages user sessions and message sending (broadcast / point‑to‑point).
Explanation: Wraps SimpMessagingTemplate to provide a unified push entry.
NotifyMessage
Role: Custom message format object.
Fields: Message ID, receiver, payload, type, status, etc.
NotifyType
Role: Defines supported notification types.
Explanation: Uses enum with type‑checking to avoid inconsistent data structures.
Usage Examples
Broadcast message:
webSocketHandler.broadcastMessage(new NotifyMessage("messageId", "messageData"));Send message to a specific user:
webSocketHandler.sendMessage(new NotifyMessage("messageId", "receiverUserId", "messageData"));Cluster Mode: Cross‑Node Session Forwarding
Core Class: StompNotifyEventListener
Supports distributed WebSocket session handling using Redisson + Redis Topic.
Processing Flow
If the current node has the target user session, push directly.
Otherwise, broadcast the event to other nodes.
Cluster Event Broadcast
Publish events to Redis Topic via Redisson.
All nodes subscribe to the Topic to achieve cluster communication.
Cross‑Node Reception
Upon receiving a broadcast event, check if the target session exists.
If present, push to the user; otherwise ignore.
Architecture Diagram (Simplified)
NotifyMessageEvent
│
▼
StompNotifyEventListener
│
┌────┴───────┐
│ │
[Session exists] [No session: broadcast]
│ │
▼ ▼
WebSocket push Redis publish
│
▼
Other nodes listen and pushMessage Persistence and Business Integration
Core Class: NotifyManager
Responsible for saving messages to the database and asynchronously pushing them to cluster nodes.
@Transactional(rollbackFor = Throwable.class)
public NotifyMessageLog saveAndPublish(NotifyMessageLog msg) {
NotifyType.valueOf(msg.getType()).checkDataType(msg.getData());
// 1. Persist message
notifyMessageLogRepository.save(msg);
// 2. Asynchronously publish event
SpringContextUtil.publishEvent(new NotifyMessageEvent(msg));
return msg;
}Summary
STOMP protocol support
Token authentication and user binding
Distributed message forwarding based on Redis
Message persistence and business decoupling
This project can serve as a reference template for enterprise‑level instant messaging/notification modules.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
