티스토리 뷰

서론

웹 소켓을 사용한 랜덤 자리배치 시스템을 만들고 있었는데, 방을 만들어서 제공하는 기능이 필요해졌습니다. 그래서 사용자가 방 별로 구독하는 방법을 찾던 중 다음과 같은 방법을 찾아 소개합니다.

본론

@DestinationVariable

Annotation that indicates a method parameter should be bound to a template variable in a destination template string. Supported on message handling methods such as @MessageMapping.
출처: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/messaging/handler/annotation/DestinationVariable.html

간단히 설명하자면 MessageMapping같은 방법으로 처리하는 메시지에서 특정 파라미터를 가져옵니다(bind). 자세한 내용을 생략했기 때문에 글로만 읽으면 분명 왜곡이 있다고 생각합니다. 그래서 직접 사용해보면서 익히시는 것이 좋을 듯 합니다.

사용 예시

내부 로직은 상관하지 않고 어노테이션만 보시면 됩니다. 가져올 MessageMapping의 파라미터를 중괄호({})로 묶어 표시합니다. 그리고 메소드의 매개변수에 @DestinationVariable 를 붙여주면 됩니다.

@Controller
public class RoomController {
    @Autowired
    private RoomService roomService;

    @MessageMapping("/{roomCode}/randomSeat")
    @SendTo("/room/{roomCode}")
    public RoomDto randomSeat(@RequestBody UserDto user, @DestinationVariable("roomCode") String roomCode){
        return roomService.changeSeat(roomService.findRoom(roomCode), user);
    }
}

@DestinationVariable를 통해 가져온 데이터는 @SendTo 어노테이션에도 적용될 수 있습니다.
위 코드에서는 MessageMapping의 roomCode 를 DestinationVariable의 roomCode와 연결되고 이것이 또한 sendTo의 randomCode와 연결됩니다. 이렇게 해서 동적으로 Destination을 설정하는 방법을 알아 봤습니다.

결론

기존에 존재하는 해결방법이 많아서 바로바로 해결할 수는 있었는데, 문제는 세세한 흐름이 어떻게 되는지는 이해하지 못하는 것 같아서 안타깝습니다. 그래도 해결했으니 만족합니다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
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 31
글 보관함