반응형
spring boot websocket 종속성 추가
implementation("org.springframework.boot:spring-boot-starter-websocket")
위가 같이 종속성을 추가하면 사용중인 spring boot의 버전과 호환되는 버전으로 설정된다.
websocket 환경설정
@Configuration
@EnableWebSocketMessageBroker
class WebsocketConfig(
private val env: Environment
) : WebSocketMessageBrokerConfigurer {
override fun configureMessageBroker(config: MessageBrokerRegistry) {
config.enableSimpleBroker("/topic") //sub
config.setApplicationDestinationPrefixes("/topic") //pub
}
/**
* /websocket/~ 이후 주소로 엔트포인트 매핑
* */
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/websocket/test").setAllowedOrigins("*")
}
}
- enableSimpleBroker() - "/topic" 접두사가 붙은 url을 구독하는 대상들에 한하여 브로커가 메세지를 전달한다.
- setApplicationDestinationPrefixes() - "/topic" 접두사가 붙은 url로 발행한 메세지만 핸들러로 라우팅
- addEndpoint() - websocket에 접근하기위한 Endpoint -> localhost:8000/websocket/test/topic 으로 발행 또는 구독시에만 메세지 발행, 구독이 가능하다.
websocket 메세지 발행 및 구독
@RestController
class ChattingController() {
@MessageMapping("/chatting/pub/{chattingRoomId}")
@SendTo("/topic/chatting/sub/{chattingRoomId}")
fun sendNewMessage(
@DestinationVariable chattingRoomId: String,
@Payload message: String
): String {
// 발행 전 동작 정의
return message
}
}
- @MessageMapping() - 위의 prefix, endpoint 설정을 포함한 입력한 url로 발행된 메세지 구독
- @SendTo() - 해당 메서드의 return값을 url을 구독하는 클라이언트에게 메세지 발행
- @DestinationVariable - 구독 및 발행 url 의 pathparameter
- @Payload - 수신된 메세지의 데이터
반응형
'Spring' 카테고리의 다른 글
[Spring Cloud] Resilience4j 를 이용한 circuitbreaker 기능 구현 (0) | 2022.03.17 |
---|---|
[Spring Boot] Websocket 통신 시 JWT 인증 (interceptor 적용) (0) | 2022.02.17 |
[Spring Boot] log4j2 보안 문제 해결 방안 - CVE-2021-44228 (0) | 2021.12.13 |
[SpringBoot] DB 연결 없이 Spring Boot 실행 시 에러 해결 (2) | 2021.12.02 |
[Spring] Spring Boot 로그 - slf4j 와 Logback, Log4j2 의 차이점 (0) | 2021.11.12 |