Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Stomp @SubscribeMapping("/user/...") with User Destination doesn't work

I need to react on a user destination subscription.

Example:

A user subscribes to /user/messages, because he wants to receive all incoming messages. Now I'd like to look up any messages for this user, which were created while he was offline, and then send them to that user.

Working code:

Client code:

stompClient.subscribe('/user/messages', function(msg){
    alert(msg.body);
});

Server code:

template.convertAndSendToUser(p.getName(), "/messages", "message content");

What I need:

It seems like it's not possible to catch an user destination subscription on server side, i.e.:

@SubscribeMapping("/user/messages")
public void test(Principal p) { 
    sendMessagesThatWereReceivedWhileUserWasOffline();
}

What I tried:

@SubscribeMapping("/messages")
public void test(Principal p) { ... }

This works, if the client subscribes to /app/messages, but it won't get called for /user/messages.

My Configuration:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/stomp").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        registry.setApplicationDestinationPrefixes("/app");
        registry.enableSimpleBroker("/queue", "/topic");
        registry.setUserDestinationPrefix("/user");
    }

    @Override
    public boolean configureMessageConverters(List<MessageConverter> messageConverters) {
        return true;
    }

    // all other methods left empty
}

Using Spring 4.1.


I can't imagine that this isn't possible. What have I missed / done wrong?

Thank you :)

like image 689
Benjamin M Avatar asked Sep 19 '14 06:09

Benjamin M


1 Answers

Define the user prefix also as an application prefix, and you'll then be able to map the subscription in your controller. Configuration:

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app", "/user");
    registry.enableSimpleBroker("/queue", "/topic");
    registry.setUserDestinationPrefix("/user");
}

Controller:

@SubscribeMapping("/messages")
public void test(Principal p) { 
    sendMessagesThatWereReceivedWhileUserWasOffline();
}
like image 165
Sergi Almar Avatar answered Nov 16 '22 16:11

Sergi Almar