일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- 리눅스
- 데커
- intelij spring config
- API
- 은행원알고리즘
- allocationSize
- 편향된 지수
- JDBC
- 컴파일 타임 상수
- 영속화
- 무한정 대기
- 쿠키
- 알고리즘
- 런타임 상수
- 커밋 되돌리기
- 파이썬
- spring
- 쉘 스크립트
- application layer
- 백준
- 프로그래머스
- JPA
- Git
- BindingResult
- m:n
- @Autowired
- DTO
- 기본키 전략
- @SubscribeMapping
- compgen
- Today
- Total
둘셋 개발!
[SPRING] STOMP @SubscribeMapping 사용법 본문
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 테스트 화면
/sub/test 로 구독하고 있다
연결을 함과 동시에 "here"이라는 데이터를 받는 것을 확인 할 수 있다.
ref
'SPRING' 카테고리의 다른 글
[Spring] @Controller사용시 핸들러의 파라미터는 누가 넣어주는 걸까? (0) | 2023.08.18 |
---|---|
[Spring] BindResult 객체 (0) | 2023.08.08 |
[Spring] RedirectAttributes와 Model차이 (+ addAttribute, addFlashAttribute) (0) | 2023.08.03 |
[오류기록] java.net.SocketException: Invalid argument (0) | 2022.09.05 |