使用 Spring 配置 STOMP
设置 Spring 的 STOMP 代理和消息处理机制,实现高效通信。
使用 Spring 配置 STOMP 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Real-Time Systems with Spring 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Spring & STOMP Configuration
Spring Boot makes building real-time applications with WebSockets and STOMP much easier. It provides powerful abstractions and auto-configuration to get you started quickly.
In this lesson, we'll learn how to set up Spring to handle STOMP messages. This involves configuring message brokers, defining endpoints, and establishing communication paths.
Activating STOMP with Spring
The first step is to enable Spring's WebSocket message broker capabilities. This is done with a single annotation: @EnableWebSocketMessageBroker.
- This annotation configures a message broker behind the scenes.
- It also sets up a Spring application context for handling STOMP messages.
- You'll typically place this on a configuration class.
Customizing Your STOMP Setup
To customize how Spring handles WebSocket and STOMP messages, you'll implement the WebSocketMessageBrokerConfigurer interface.
This interface provides methods that allow you to:
- Configure the message broker.
- Register STOMP endpoints.
- Add interceptors and customize message converters.
Setting Up the Message Broker
The message broker routes messages to their intended recipients. Spring provides a "simple" in-memory broker for basic needs.
You configure it in the configureMessageBroker method:
enableSimpleBroker(): Activates the in-memory broker.- Paths like
/topicare for public, publish-subscribe messages. - Paths like
/queueare for private, point-to-point messages.
Simple Broker Example
Here's how to set up the basic in-memory message broker with /topic and /queue destinations. This will allow clients to subscribe to public topics and send private messages.
package com.coddykit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
}
// Endpoints will be added later
}Client-to-Server Paths
When a client sends a message to the server, it usually targets a specific server-side handler. We define a prefix for these messages using setApplicationDestinationPrefixes().
- For example, if the prefix is
/app, clients send messages to paths like/app/chat.sendMessage. - These messages are then routed to methods annotated with
@MessageMappingon the server.
App Destination Prefix Example
Let's update our configuration to include an application destination prefix. This tells Spring which messages are intended for server-side methods.
package com.coddykit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic", "/queue");
// Messages from clients for the server will start with /app
config.setApplicationDestinationPrefixes("/app");
}
// Endpoints will be added later
}Defining WebSocket Connection Point
Clients need a specific HTTP endpoint to initiate the WebSocket handshake. This is where they first connect before STOMP messaging begins.
You define this endpoint using registerStompEndpoints():
addEndpoint("/ws"): Makes the endpoint available athttp://localhost:8080/ws.withSockJS(): Enables SockJS fallback options for browsers that don't fully support WebSockets.
Complete STOMP Configuration
Here's the complete configuration class, combining the message broker setup, application destination prefix, and the STOMP endpoint registration. This is the foundation for your Spring STOMP application.
package com.coddykit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Messages for client subscriptions (server to client)
config.enableSimpleBroker("/topic", "/queue");
// Messages from clients to server-side handlers
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// The HTTP endpoint for WebSocket handshake
registry.addEndpoint("/ws").withSockJS();
}
}Configuration Check
You've learned about different prefixes in Spring STOMP configuration. It's crucial to understand their roles.
Summary of Configuration
You've successfully learned how to configure Spring for STOMP messaging! Here's a quick recap:
@EnableWebSocketMessageBroker: Activates WebSocket and STOMP support.WebSocketMessageBrokerConfigurer: Interface for customizing the setup.configureMessageBroker(): Sets up the message broker (e.g.,enableSimpleBroker("/topic", "/queue")) and application destination prefixes (e.g.,setApplicationDestinationPrefixes("/app")).registerStompEndpoints(): Defines the WebSocket handshake URL (e.g.,addEndpoint("/ws").withSockJS()).
These steps lay the foundation for building powerful real-time features with Spring and STOMP!
常见问题解答
「使用 Spring 配置 STOMP」课时是免费的吗?
是的 — 「使用 Spring 配置 STOMP」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。
「使用 Spring 配置 STOMP」这节课中我会学到什么?
设置 Spring 的 STOMP 代理和消息处理机制,实现高效通信。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 Spring 配置 STOMP」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?
能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- STOMP 协议简介
- 使用 Spring 配置 STOMP
- 发送和接收 STOMP 消息
- 使用 Spring Security 保护 STOMP 端点