简体   繁体   中英

How to subscribe an internal Spring Boot/Simple Broker topic queue?

I need to subscribe the internal spring boot topic /user/exchange/amq.direct/chat.message to creat a bot that will subscribe a topic queue and answer the messages.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer {

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {

    registry.addEndpoint("/ws").setAllowedOrigins("*").withSockJS();

}

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
    // use the /topic prefix for outgoing WebSocket communication
    config.enableSimpleBroker("/queue/", "/topic/", "/exchange/");

    // use the /app prefix for others
    config.setApplicationDestinationPrefixes("/app");
}

}

My Controller:

    @MessageMapping("/chat.message")
public ChatMessage filterMessage(@Payload ChatMessage message, Principal principal) {

    message.setUsername(principal.getName());

    return message;
}

@MessageMapping("/chat.private.{username}")
public void filterPrivateMessage(@Payload ChatMessage message, @DestinationVariable("username") String username, Principal principal) {

    message.setUsername(principal.getName());

    simpMessagingTemplate.convertAndSend("/user/" + username + "/exchange/amq.direct/chat.message", message);

}

How to subscribe a internal queue/topic that I put the message by SimpMessagingTemplate?

You can use the @sendTo annotation and @DestinationVariable to distinguish which user you want to subscribe to. I use this method to share my current subscription points. I'll give you one of my setup codes and a simple example.

It inherits from AbstractWebSocketMessageBrokerConfigurer and its configuration is final.

@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/webSocket").setAllowedOrigins("*").withSockJS();
}

This code can only send a message to the user who subscribes to a specific path and the path that the client sends the message to.

@MessageMapping(value = "/question/detail/{questionId}/message")
@SendTo("/question/detail/{questionId}")
public MessageDto message(@DestinationVariable Long questionId, MessageDto messageDto) {
    return messageDto;
}

Is the answer you want?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM