WebSockets & Real-Time Systems with Spring · Lektion

RabbitMQ/Kafka integrieren

Konfigurieren Sie Spring WebSockets für die Nutzung externer Message-Broker zur Kommunikation zwischen Servern.

Lektion 2 von 411 Schritte

RabbitMQ/Kafka integrieren ist eine kostenlose WebSockets & Real-Time Systems with Spring-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des WebSockets & Real-Time Systems with Spring-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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.

Kostenlos starten

Lerne WebSockets & Real-Time Systems with Spring mit einem KI-Tutor — kostenlos

Schreibe und führe echten Code in deinem Browser aus, bekomme sofortige Hilfe von einem 24/7 KI-Tutor und setze dein Lernen im Web oder in der App fort.

Kurse
12
Lektionen
48

Häufig gestellte Fragen

Ist die Lektion „RabbitMQ/Kafka integrieren“ kostenlos?

Ja — der vollständige Text von „RabbitMQ/Kafka integrieren“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des WebSockets & Real-Time Systems with Spring-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der WebSockets & Real-Time Systems with Spring-Kurs umfasst insgesamt 4 Lektionen.

Was lerne ich in „RabbitMQ/Kafka integrieren“?

Konfigurieren Sie Spring WebSockets für die Nutzung externer Message-Broker zur Kommunikation zwischen Servern. Du übst WebSockets & Real-Time Systems with Spring mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um WebSockets & Real-Time Systems with Spring zu starten?

Keine Vorkenntnisse erforderlich. WebSockets & Real-Time Systems with Spring auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.

Wie lange dauert die Lektion „RabbitMQ/Kafka integrieren“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser WebSockets & Real-Time Systems with Spring-Lektion Code schreiben und ausführen?

Ja. Jede WebSockets & Real-Time Systems with Spring-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Notwendigkeit externer Message-Broker
  2. RabbitMQ/Kafka integrieren
  3. Verteilte WebSocket-Architekturen
  4. STOMP-Broker-Relay konfigurieren
← Zurück zu WebSockets & Real-Time Systems with Spring