SpringBoot简单使用Stomp

下面是一个使用 STOMP 协议的 Spring Boot 应用示例,包含三个 WebSocket 端点。每个端点都有特定的功能。代码中包含中文注释,帮助你理解每个部分的作用。

1. 添加依赖

首先,确保在 pom.xml 中添加了 WebSocket 和 Spring Messaging 的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 配置 WebSocket 和 STOMP

创建一个配置类来注册多个 WebSocket 端点:

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;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // 配置消息代理,启用简单代理,支持/topic和/queue
        config.enableSimpleBroker("/topic", "/queue");
        // 设置应用程序目的地前缀
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // 注册三个不同的WebSocket端点,支持SockJS
        registry.addEndpoint("/ws-endpoint1").withSockJS();
        registry.addEndpoint("/ws-endpoint2").withSockJS();
        registry.addEndpoint("/ws-endpoint3").withSockJS();
    }
}

3. 创建控制器

创建一个控制器来处理不同的消息:

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class MessageController {

    // 处理来自客户端的消息,路径为/app/message1
    @MessageMapping("/message1")
    // 将处理结果发送到/topic/messages1
    @SendTo("/topic/messages1")
    public String handleMessage1(String message) {
        return "Endpoint1: " + message;
    }

    // 处理来自客户端的消息,路径为/app/message2
    @MessageMapping("/message2")
    // 将处理结果发送到/topic/messages2
    @SendTo("/topic/messages2")
    public String handleMessage2(String message) {
        return "Endpoint2: " + message;
    }

    // 处理来自客户端的消息,路径为/app/message3
    @MessageMapping("/message3")
    // 将处理结果发送到/topic/messages3
    @SendTo("/topic/messages3")
    public String handleMessage3(String message) {
        return "Endpoint3: " + message;
    }
}

4. 客户端示例

在客户端(例如,使用 JavaScript)中,连接到不同的 WebSocket 端点:

function connectToEndpoint(endpoint, messagePath, subscriptionPath) {
    const socket = new SockJS(endpoint);
    const stompClient = Stomp.over(socket);

    stompClient.connect({}, function (frame) {
        console.log('已连接到 ' + endpoint + ': ' + frame);

        // 订阅主题
        stompClient.subscribe(subscriptionPath, function (message) {
            console.log('收到消息: ' + message.body);
        });

        // 发送消息到服务器
        stompClient.send(messagePath, {}, "来自 " + endpoint + " 的消息");
    });
}

// 连接到每个端点
connectToEndpoint('/ws-endpoint1', '/app/message1', '/topic/messages1');
connectToEndpoint('/ws-endpoint2', '/app/message2', '/topic/messages2');
connectToEndpoint('/ws-endpoint3', '/app/message3', '/topic/messages3');

代码解释

  • WebSocketConfig:配置类用于注册 WebSocket 端点和配置消息代理。

    • enableSimpleBroker("/topic", "/queue"):启用简单的内存消息代理,支持 /topic/queue 作为消息目的地。
    • setApplicationDestinationPrefixes("/app"):设置应用程序目的地前缀,客户端发送的消息路径应以 /app 开头。
    • registerStompEndpoints:注册三个 WebSocket 端点,支持 SockJS。
  • MessageController:控制器类处理来自客户端的消息。

    • @MessageMapping:映射客户端发送的消息路径。
    • @SendTo:指定处理后的消息发送到的目的地。
  • 客户端代码:使用 SockJS 和 STOMP.js 连接到 WebSocket 端点,订阅主题并发送消息。

通过这种方式,你可以在 Spring Boot 中配置多个 WebSocket 端点,并处理来自不同端点的消息。每个端点和消息路径都有特定的功能,便于扩展和管理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

堕落年代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值