Spring/기타 여러가지
WebSocketMessageBroker관련 01
by doriver
2025. 1. 29.
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfigV02 implements WebSocketMessageBrokerConfigurer {
@Override // 메시지 브로커 설정
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/chatRoom"); // 클라이언트가 구독할 수 있는 메시지 브로커를 설정
registry.setApplicationDestinationPrefixes("/chatApp"); // 클라이언트가 보낸 메시지를 컨트롤러에서 처리
}
@Override // STOMP 엔드포인트 등록
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chatRoom-v02-websocket"); // 해당 경로에서 WebSocket연결을 수락
}
}
public class WebMvcStompEndpointRegistry implements StompEndpointRegistry {
private final WebSocketHandler webSocketHandler;
private final TaskScheduler sockJsScheduler;
private final SubProtocolWebSocketHandler subProtocolWebSocketHandler;
private final StompSubProtocolHandler stompHandler;
private final List<WebMvcStompWebSocketEndpointRegistration> registrations = new ArrayList();
public StompWebSocketEndpointRegistration addEndpoint(String... paths) {
this.subProtocolWebSocketHandler.addProtocolHandler(this.stompHandler);
WebMvcStompWebSocketEndpointRegistration registration = new WebMvcStompWebSocketEndpointRegistration(paths, this.webSocketHandler, this.sockJsScheduler);
this.registrations.add(registration);
return registration;
}
}
public class WebMvcStompWebSocketEndpointRegistration implements StompWebSocketEndpointRegistration {
private final List<HandshakeInterceptor> interceptors = new ArrayList();
public WebMvcStompWebSocketEndpointRegistration(String[] paths
, WebSocketHandler webSocketHandler, TaskScheduler sockJsTaskScheduler) {
Assert.notEmpty(paths, "No paths specified");
Assert.notNull(webSocketHandler, "WebSocketHandler must not be null");
this.paths = paths;
this.webSocketHandler = webSocketHandler;
this.sockJsTaskScheduler = sockJsTaskScheduler;
}
public StompWebSocketEndpointRegistration addInterceptors(HandshakeInterceptor... interceptors) {
if (!ObjectUtils.isEmpty(interceptors)) {
this.interceptors.addAll(Arrays.asList(interceptors));
}
return this;
}
}