spring.io/guides/gs/messaging-stomp-websocket/#scratch
Using WebSocket to build an interactive web application
this guide is designed to get you productive as quickly as possible and using the latest Spring project releases and techniques as recommended by the Spring team
spring.io
공식 페이지의 가이드를 참고하여 따라 진행..
spring에서는 2가지 방식으로 WebSocket을 구현 할 수 있다.
1. WebSocket 직접 처리 -> 복잡하다 !
2. Stomp 사용
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/gs-guide-websocket").withSockJS();
}
}
- pub/sub 모델을 따르며, 토픽에 따라 메시지를 전달해야하는 사용자를 구분한다.
- broker 함수로 topic에 대한 prefix과 메시지를 수신하는 handler의 메시지 prefix를 설정해준다.
@Controller
public class GreetingController {
@MessageMapping("/hello")
@SendTo("/topic/greetings")
public Greeting greeting(HelloMessage message) throws Exception {
Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + HtmlUtils.htmlEscape(message.getName()) + "!");
}
}
- 설정 파트에서 setApplicationDestinationPrefix("/app")으로 설정했기 때문에, 메시지를 보낼 때
/app/hello로 보내면 handler가 메시지를 수신한다.
- 메시지가 수신 된후 지정된 @SendTo("/topic/greetings") 을 구독하는 클라이언트에게 메시지를 전달한다.
'Back-end > spring' 카테고리의 다른 글
의존관계 주입 (0) | 2021.02.16 |
---|---|
컴포넌트 스캔 (0) | 2021.02.08 |
애노테이션 & XML 기반 설정 사용 (0) | 2021.02.08 |
스프링 컨테이너 (0) | 2021.02.08 |
객체지향 원리 적용 (0) | 2021.02.08 |