둘셋 개발!

[SPRING] STOMP @SubscribeMapping 사용법 본문

SPRING

[SPRING] STOMP @SubscribeMapping 사용법

23 2023. 10. 15. 14:44

Intro.

채팅 서비스를 개발하기 위해서 STOMP를 도입하는 중이였다.

채팅을 보내고 받는 것 말고 채팅 내역 조회, 채팅방 목록 등의 데이터를 보내줄 때는 어떻게 보내줄까 하다가

@SubscribeMapping을 적절히 사용하면 될 것 같았다.

 

이번 포스팅은 @SubscribeMapping이 무엇인지, 어떻게 사용하는지 등을 정리해보겠다.


@SubscribeMapping 이란?

stomp에서 요청-응답을 하는데에 유용하게 쓰인다. (예를 들면 application UI를 초기화)

return으로 값을 내보내면 broker을 통하지 않고 다이렉트로 연결된 클라이언트에게 데이터를 보내준다...!

만약 broker을 통해서 데이터를 보내고 싶으면 @SendTo를 사용하면 된다.

 

 


@SubscribeMapping 사용 예시

저는 apic으로 테스트를 진행했습니다!!

 

Config

@Configuration
@EnableWebSocketMessageBroker
public class ChatConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/chat").setAllowedOriginPatterns("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {

        registry.enableSimpleBroker("/sub");
        registry.setApplicationDestinationPrefixes("/pub", "/sub");
    }
}

 

다른 레퍼런스를 보면 구독을 하는 쪽을 '/topic' 으로 하고 메세지를 보내는 쪽을 '/app' 이라고 정해져있지만

나한테 더 직관적으로 다가오는 단어를 선택했다.

'/topic' 은  '/sub' 으로 바꾸었고 '/app' 은 '/pub'으로 바꾸었다. 

sub은 subscribe을 의미하고 pub은 publish를 의미한다.

 

여기서 setApplicationDestinationPrefixes에 '/sub'도 꼭 추가해야한다!

그래야지 @SubscribeMapping 메서드와 상호작용할 수 있다.

(제가 이걸 놓쳐서 많은 삽질을 했습니다...🥹)

 

Controller

@Controller
public class StompController {

    @SubscribeMapping("/test")
    public String test() {
        return "here";
    }
}

/test을 구독한 클라이언트에게 "here" 데이터를 보내준다.

 

 

apic 테스트 화면

apic 화면

/sub/test 로 구독하고 있다

연결을 함과 동시에 "here"이라는 데이터를 받는 것을 확인 할 수 있다.

 


ref

https://docs.spring.io/spring-framework/docs/5.0.4.RELEASE/spring-framework-reference/web.html#websocket-stomp-handle-annotations

 

Web on Servlet Stack

This part of the reference documentation covers support for Servlet stack, WebSocket messaging that includes raw WebSocket interactions, WebSocket emulation via SockJS, and pub-sub messaging via STOMP as a sub-protocol over WebSocket. 4.1. Introduction The

docs.spring.io

 

https://stackoverflow.com/questions/38323193/what-is-setapplicationdestinationprefixes-being-used-for

 

What is setApplicationDestinationPrefixes being used for?

I followed a tutorial to implement websockets in my Java Spring application. It is working fine so far but I really would like to understand what this is used for: config.

stackoverflow.com

https://stackoverflow.com/questions/51370668/spring-stomp-over-websocket-subscribemapping-not-working

 

Spring stomp over websocket SubscribeMapping not working

I'm trying to configure subscription mapping for stomp over websockets in a spring boot application without any luck. I'm fairly certian I have the stomp/websocket stuff configured correctly as I am

stackoverflow.com