0Pricing
WebSockets & Real-Time Systems with Spring · 강의

Spring에서 STOMP 구성하기

효율적인 통신을 위해 Spring의 STOMP 브로커와 메시지 처리 메커니즘을 설정합니다.

Spring에서 STOMP 구성하기은(는) 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개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Spring & STOMP Configuration

Spring Boot makes building real-time applications with WebSockets and STOMP much easier. It provides powerful abstractions and auto-configuration to get you started quickly.

In this lesson, we'll learn how to set up Spring to handle STOMP messages. This involves configuring message brokers, defining endpoints, and establishing communication paths.

Activating STOMP with Spring

The first step is to enable Spring's WebSocket message broker capabilities. This is done with a single annotation: @EnableWebSocketMessageBroker.

  • This annotation configures a message broker behind the scenes.
  • It also sets up a Spring application context for handling STOMP messages.
  • You'll typically place this on a configuration class.

Customizing Your STOMP Setup

To customize how Spring handles WebSocket and STOMP messages, you'll implement the WebSocketMessageBrokerConfigurer interface.

This interface provides methods that allow you to:

  • Configure the message broker.
  • Register STOMP endpoints.
  • Add interceptors and customize message converters.

Setting Up the Message Broker

The message broker routes messages to their intended recipients. Spring provides a "simple" in-memory broker for basic needs.

You configure it in the configureMessageBroker method:

  • enableSimpleBroker(): Activates the in-memory broker.
  • Paths like /topic are for public, publish-subscribe messages.
  • Paths like /queue are for private, point-to-point messages.

Simple Broker Example

Here's how to set up the basic in-memory message broker with /topic and /queue destinations. This will allow clients to subscribe to public topics and send private messages.

package com.coddykit;

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;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
    }
    // Endpoints will be added later
}

Client-to-Server Paths

When a client sends a message to the server, it usually targets a specific server-side handler. We define a prefix for these messages using setApplicationDestinationPrefixes().

  • For example, if the prefix is /app, clients send messages to paths like /app/chat.sendMessage.
  • These messages are then routed to methods annotated with @MessageMapping on the server.

App Destination Prefix Example

Let's update our configuration to include an application destination prefix. This tells Spring which messages are intended for server-side methods.

package com.coddykit;

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;

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic", "/queue");
        // Messages from clients for the server will start with /app
        config.setApplicationDestinationPrefixes("/app");
    }
    // Endpoints will be added later
}

Defining WebSocket Connection Point

Clients need a specific HTTP endpoint to initiate the WebSocket handshake. This is where they first connect before STOMP messaging begins.

You define this endpoint using registerStompEndpoints():

  • addEndpoint("/ws"): Makes the endpoint available at http://localhost:8080/ws.
  • withSockJS(): Enables SockJS fallback options for browsers that don't fully support WebSockets.

Complete STOMP Configuration

Here's the complete configuration class, combining the message broker setup, application destination prefix, and the STOMP endpoint registration. This is the foundation for your Spring STOMP application.

package com.coddykit;

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

@SpringBootApplication
public class MainApplication {
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // Messages for client subscriptions (server to client)
        config.enableSimpleBroker("/topic", "/queue");
        // Messages from clients to server-side handlers
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // The HTTP endpoint for WebSocket handshake
        registry.addEndpoint("/ws").withSockJS();
    }
}

Configuration Check

You've learned about different prefixes in Spring STOMP configuration. It's crucial to understand their roles.

Summary of Configuration

You've successfully learned how to configure Spring for STOMP messaging! Here's a quick recap:

  • @EnableWebSocketMessageBroker: Activates WebSocket and STOMP support.
  • WebSocketMessageBrokerConfigurer: Interface for customizing the setup.
  • configureMessageBroker(): Sets up the message broker (e.g., enableSimpleBroker("/topic", "/queue")) and application destination prefixes (e.g., setApplicationDestinationPrefixes("/app")).
  • registerStompEndpoints(): Defines the WebSocket handshake URL (e.g., addEndpoint("/ws").withSockJS()).

These steps lay the foundation for building powerful real-time features with Spring and STOMP!

자주 묻는 질문

“Spring에서 STOMP 구성하기” 강의는 무료인가요?

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

“Spring에서 STOMP 구성하기”에서 뭘 배우나요?

효율적인 통신을 위해 Spring의 STOMP 브로커와 메시지 처리 메커니즘을 설정합니다. 브라우저에서 직접 실행하는 실습 코드로 WebSockets & Real-Time Systems with Spring을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“Spring에서 STOMP 구성하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 WebSockets & Real-Time Systems with Spring 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 WebSockets & Real-Time Systems with Spring 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. STOMP 프로토콜 소개
  2. Spring에서 STOMP 구성하기
  3. STOMP 메시지 송수신
  4. Spring Security로 STOMP 엔드포인트 보호
← WebSockets & Real-Time Systems with Spring(으)로 돌아가기