WebSockets & Real-Time Systems with Spring · 강의

RabbitMQ/Kafka 통합

서버 간 통신을 위해 Spring WebSockets가 외부 메시지 브로커를 사용하도록 구성합니다.

레슨 2/411개 단계

RabbitMQ/Kafka 통합은(는) CoddyKit의 무료 WebSockets & Real-Time Systems with Spring 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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.

무료로 시작

AI 튜터와 함께 WebSockets & Real-Time Systems with Spring을(를) 배우세요 — 무료

브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.

코스
12
레슨
48

자주 묻는 질문

“RabbitMQ/Kafka 통합” 강의는 무료인가요?

네 — “RabbitMQ/Kafka 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 WebSockets & Real-Time Systems with Spring 강의 전체를 잠금 해제할 수 있습니다. WebSockets & Real-Time Systems with Spring 강의에는 총 4개의 강의가 포함되어 있습니다.

“RabbitMQ/Kafka 통합”에서 뭘 배우나요?

서버 간 통신을 위해 Spring WebSockets가 외부 메시지 브로커를 사용하도록 구성합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

WebSockets & Real-Time Systems with Spring을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 WebSockets & Real-Time Systems with Spring은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“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(으)로 돌아가기