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

后端 未结 5 787
别跟我提以往
别跟我提以往 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:07

    Hi Mert though your question is ask over 4 years ago but I'll still try to answer it since I scratched my head on the same problem recently and finally solved it.

    The key part here is @SubscribeMapping is a one-time request-response exchange, therefore the try1() method in your controller will be triggered only once right after client codes runs

    stompClient.subscribe('/topic/greetings', callback)
    

    after that there's no way to trigger try1() by stompClient.send(...)

    Another problem here is the controller is part of the application message handler, which receives destination with prefix /app ripped, so in order to reach @SubscribeMapping("/topic/greetings") you actually have to write client code like this

    stompClient.subscribe('/app/topic/greetings', callback)
    

    since conventionally topic is mapped with brokers to avoid ambiguity I recommend to modify your code to

    @SubscribeMapping("/greetings")
    
    stompClient.subscribe('/app/greetings', callback)
    

    and now console.log('RECEIVED !!!') should work.

    The official doc also recommends use case scenario of @SubscribeMapping on initial UI rendering.

    When is this useful? Assume that the broker is mapped to /topic and /queue, while application controllers are mapped to /app. In this setup, the broker stores all subscriptions to /topic and /queue that are intended for repeated broadcasts, and there is no need for the application to get involved. A client could also also subscribe to some /app destination, and a controller could return a value in response to that subscription without involving the broker without storing or using the subscription again (effectively a one-time request-reply exchange). One use case for this is populating a UI with initial data on startup.

提交回复
热议问题