STOMP (Simple Text Oriented Messaging Protocol)는 WeSocket 상위에서 동작하는 메시징 프로토콜이다. WebSocket은 단순히 소켓 연결을 제공하지만, STOMP를 사용하면 메시지 브로커와 연동하거나, 구독/발행(Publish/Subscribe) 패턴을 쉽게 구현할 수 있다.
이 패턴에서는 메시지 송신자(Publisher)와 수신자(Subscriber) 간에 직접적인 연결 없이, 주제(Topic)을 통해 메시지를 주고 받는다.
어떻게 동작하는가?
- 발행자(Publisher): 특정 주제에 메시지를 발행한다.
- 구독자(Subscriber): 관심 있는 주제를 구독한다.
- 메시지 전달: 발행된 메시지는 해당 주제를 구독한 모든 구독자에게 전달된다.
예시:
/topic/alerts를 구독한다고 가정한다./topic/alerts에 메시지를 발행한다./topic/alerts를 구독한 A와 B는 실시간으로 해당 메시지를 수신한다.메시지 브로커는 발행된 메시지를 중개하고 관리해 주는 역할을 하는 중앙 허브이다. 발행된 메시지를 브로커가 받아서 구독자에게 자동으로 전달해 주므로, 개발자는 발행과 구독만 신경 쓰면 된다.
Spring에서 STOMP를 사용하면 내장된 메시지 브로커를 활용하거나, 외부 메시지 브로커(RabbitMQ 등)을 연동할 수 있다. 브로커는 다음과 같은 상황에 필요하다.
/topic/notifications 주제를 구독한다./topic/notifications에 새로운 메시지를 발행한다.<!-- RabbitMQ 의존성 추가 (pom.xml) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
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;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 외부 메시지 브로커를 사용하는 경우
config.enableStompBrokerRelay("/topic", "/queue")
.setRelayHost("localhost") // RabbitMQ 서버 주소
.setRelayPort(61613) // RabbitMQ 포트
.setClientLogin("guest") // 사용자 이름
.setClientPasscode("guest"); // 비밀번호
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
}