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.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
How to Integrate WebSocket + STOMP in Spring Boot for Scalable Real‑Time Messaging

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:

Demo screenshot
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 interceptor

StompWebsocketConfig

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 push

Message 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

real-time messagingRedisSpring BootWebSocketClusterstomp
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.