Reputation: 1329
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?
Upvotes: 3
Views: 2322
Reputation: 11
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?
Upvotes: 1