0Pricing
WebSockets & Real-Time Systems with Spring · 课时

集成 RabbitMQ/Kafka

配置 Spring WebSockets 使用外部消息代理,实现服务器间通信。

集成 RabbitMQ/Kafka 是 CoddyKit 上的免费 WebSockets & Real-Time Systems with Spring 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Real-Time Systems with Spring 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Scaling with External Brokers

When your WebSocket application runs on multiple server instances, an in-memory message broker isn't enough. You need an external message broker to coordinate messages across all instances.

This ensures that a message sent to one server can be received by a client connected to *any* server in your cluster, enabling true horizontal scaling.

Spring's Broker Bridge

Spring provides a powerful abstraction called the STOMP Broker Relay. This allows your Spring WebSocket application to delegate message routing to an external STOMP-compatible message broker.

Your application acts as a client to the external broker, sending and receiving messages on behalf of connected WebSocket clients.

RabbitMQ: A STOMP Broker

RabbitMQ is a popular open-source message broker that can be configured to act as a STOMP broker by enabling its STOMP plugin. This makes it an excellent choice for scaling Spring WebSocket applications.

  • Producers: Your Spring app sends messages to RabbitMQ.
  • Consumers: Your Spring app receives messages from RabbitMQ.
  • STOMP Plugin: Translates WebSocket STOMP frames to AMQP and vice-versa.

Add RabbitMQ Dependency

To enable Spring to communicate with RabbitMQ, you need to add the spring-boot-starter-websocket and spring-boot-starter-amqp dependencies to your project's build.gradle or pom.xml.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    implementation 'org.springframework.boot:spring-boot-starter-amqp'
    // ... other dependencies
}

Configure RabbitMQ Broker Relay

In your WebSocketConfig, use enableStompBrokerRelay() to tell Spring to use RabbitMQ's STOMP plugin as the message broker. Remember to set the correct host, port, and credentials.

Try running this full Spring Boot application:

package com.coddykit.websocket;

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;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

@SpringBootApplication
public class Main {
    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
        System.out.println("Spring Boot WebSocket app with RabbitMQ broker relay started.");
        System.out.println("Ensure RabbitMQ with STOMP plugin is running on localhost:61613.");
    }

    @Configuration
    @EnableWebSocketMessageBroker
    static class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

        @Override
        public void configureMessageBroker(MessageBrokerRegistry config) {
            config.enableStompBrokerRelay("/topic", "/queue")
                  .setRelayHost("localhost") // Or your RabbitMQ host
                  .setRelayPort(61613) // Default STOMP port for RabbitMQ plugin
                  .setClientLogin("guest")
                  .setClientPasscode("guest");
            config.setApplicationDestinationPrefixes("/app");
            config.setUserDestinationPrefix("/user");
        }

        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws").withSockJS();
        }
    }
}

Kafka for Inter-Server Sync

While RabbitMQ can act as a direct STOMP broker relay, Apache Kafka is typically used for different types of inter-server communication in a scalable WebSocket architecture.

Instead of Kafka being the direct STOMP broker, individual Spring WebSocket instances might use Kafka to broadcast internal events or messages to other instances in the cluster.

Kafka's Role in a Cluster

Imagine you have multiple WebSocket servers. When a message arrives at Server A, and the recipient is connected to Server B, Server A can publish the message to a Kafka topic.

Server B (and all other servers) can consume from this topic, identify the message for its client, and forward it. This makes Kafka an excellent backend for distributed message coordination.

Add Kafka Dependency

To enable Spring to interact with Kafka for backend messaging, you need the spring-kafka dependency.

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-websocket'
    implementation 'org.springframework.kafka:spring-kafka'
    // ... other dependencies
}

Kafka Application Properties

When using Kafka for inter-server messaging, you'd configure Kafka broker details and consumer/producer properties in your application.properties file.

spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.consumer.group-id=websocket-cluster
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer

Broker Configuration Check

You're setting up a Spring Boot WebSocket application to use an external STOMP-compatible message broker to support multiple server instances. Which method in WebSocketMessageBrokerConfigurer is primarily used to configure Spring to connect to this external broker?

Recap: External Brokers

We've learned how external message brokers are crucial for scaling WebSocket applications. Spring's enableStompBrokerRelay() simplifies integrating with brokers like RabbitMQ (when its STOMP plugin is enabled).

For Kafka, while not a direct STOMP broker relay, it serves as a powerful backend for inter-server communication, allowing WebSocket instances to coordinate and distribute messages across a cluster, enabling robust scaling.

常见问题解答

「集成 RabbitMQ/Kafka」课时是免费的吗?

是的 — 「集成 RabbitMQ/Kafka」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Real-Time Systems with Spring 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Real-Time Systems with Spring 课程共包含 4 节课。

「集成 RabbitMQ/Kafka」这节课中我会学到什么?

配置 Spring WebSockets 使用外部消息代理,实现服务器间通信。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Real-Time Systems with Spring,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Real-Time Systems with Spring 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Real-Time Systems with Spring 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「集成 RabbitMQ/Kafka」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 WebSockets & Real-Time Systems with Spring 课中编写并运行代码吗?

能。每节 WebSockets & Real-Time Systems with Spring 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用外部消息代理的必要性
  2. 集成 RabbitMQ/Kafka
  3. 分布式 WebSocket 架构
  4. 配置 STOMP 代理中继
← 返回 WebSockets & Real-Time Systems with Spring