Does Spring @SubscribeMapping really subscribe the client to some topic?

后端 未结 5 771
别跟我提以往
别跟我提以往 2021-01-30 02:45

I am using Spring Websocket with STOMP, Simple Message Broker. In my @Controller I use method-level @SubscribeMapping, which should subscribe the clien

5条回答
  •  后悔当初
    2021-01-30 03:17

    So having both:

    • Using a topic to handle subscription
    • Using @SubscribeMapping on that topic to deliver a connection-response

    does not work as you experienced (as well as me).

    The way to solve your situation (as I did mine) is:

    1. Remove the @SubscribeMapping - it only works with /app prefix
    2. Subscribe to the /topic just as you would naturally (w/o /app prefix)
    3. Implement an ApplicationListener

      1. If you want to directly reply to a single client use a user destination (see websocket-stomp-user-destination or you could also subscribe to a sub-path e.g. /topic/my-id-42 then you can send a message to this subtopic (I don't know about your exact use case, mine is that I have dedicated subscriptions and I iterate over them if I want to do a broadcast)

      2. Send a message in your onApplicationEvent method of the ApplicationListener as soon as you receive a StompCommand.SUBSCRIBE

    Subscription Event Handler:

    @Override
      public void onApplicationEvent(SessionSubscribeEvent event) {
          Message message = event.getMessage();
          StompHeaderAccessor accessor = StompHeaderAccessor.wrap(message);
          StompCommand command = accessor.getCommand();
          if (command.equals(StompCommand.SUBSCRIBE)) {
              String sessionId = accessor.getSessionId();
              String stompSubscriptionId = accessor.getSubscriptionId();
              String destination = accessor.getDestination();
              // Handle subscription event here
              // e.g. send welcome message to *destination*
           }
      }
    

提交回复
热议问题