Search code examples
javaspringactivemq-classicstompspring-websocket

Routing subscriptions in Spring Websocket STOMP with ActiveMQ


I have configured Spring STOMP with ActiveMQ, it works fine. But, is there any chance to make client's subscription routing?

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.enableStompBrokerRelay("/topic");
    registry.setApplicationDestinationPrefixes("/app");
}

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

What I want to achieve is two queues for notifications (on frontend) - one for admin users, and one for normal users. Users do not send any messages, only receive ones from server. Let's say that any user can send following subscription request:

// app is application destination prefix
client.subscribe('/app/notificator', ...);

Server should routes this request to ActiveMQ:

/topic/notificator/admin - if logged user is of role admin, or
/topic/notificator/user - if logged user is of role user

How to configure Spring to make such routing policy?


Solution

  • Ok, I solved it with controller:

    @Controller
    public class QueueController {
    
        @SubscribeMapping("/notificator")
        public String getNotificatorQueue(Principal principal) {
            String role = // get role from principal
            return "/topic/notificator/" + role;
        }
    
    }
    

    This way I can get url for user subscription, which I'll invoke on "/app/notificator" repsonse.