3

I am using spring-websocket to push messages to browser clients.

My setup is almost identical to the one in the portfolio example and I send out messages by using MessageSendingOperations:

MessageSendingOperations<String> messagingTemplate = //...;
this.messagingTemplate.convertAndSend("/topic/data/1", message);

This works perfectly.

But I would also like to be able to subscribe to the same messages internally.

MessageReceivingOperations almost looks like the one to use, but it only seems to support pulling messages. I would much prefer having the messages pushed to my service.

SubscribableChannel.subscribe() also looks promising, but how do I get hold of the correct channel?

I would really like to be able to call something like

messagingTemplate.subscribe("/topic/data/*", 
                            new MessageHandler<String>{
                                public void handleMessage(String s){
                                  // process message
                                }
                            });
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189

1 Answers1

1

The following works for me, but it would be nice with a more direct way to do it:

public interface MessageHandler<T> {
    public void handleMessage(T message);
}

@Autowired
private AbstractSubscribableChannel brokerChannel;

private PathMatcher pathMatcher = new AntPathMatcher();

private <T> void subscribe(final String topic, final Handler<T> handler, final Class<T> messageClass){
    brokerChannel.subscribe(new MessageHandler() {
        @Override
        public void handleMessage(Message<?> message) throws MessagingException {
            SimpMessageHeaderAccessor headers = SimpMessageHeaderAccessor.wrap(message);
            final String destination = headers.getDestination();
            if(pathMatcher.match(topic, destination)) {
                final T messageObject = (T) messageConverter.fromMessage(message, messageClass);
                handler.handleMessage(messageObject);
            }
        }
    });
}
Rasmus Faber
  • 48,631
  • 24
  • 141
  • 189