0Pricing
WebSockets & Real-Time Systems with Spring · Lección

Integración con RabbitMQ/Kafka

Configure Spring WebSockets para utilizar brokers de mensajes externos en la comunicación entre servidores.

Integración con RabbitMQ/Kafka es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «Integración con RabbitMQ/Kafka» es gratis?

Sí — el texto completo de «Integración con RabbitMQ/Kafka» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

¿Qué aprenderé en «Integración con RabbitMQ/Kafka»?

Configure Spring WebSockets para utilizar brokers de mensajes externos en la comunicación entre servidores. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?

No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Integración con RabbitMQ/Kafka»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?

Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Necesidad de brokers de mensajes externos
  2. Integración con RabbitMQ/Kafka
  3. Arquitecturas WebSocket distribuidas
  4. Configuración del broker relay de STOMP
← Volver a WebSockets & Real-Time Systems with Spring