Spring Stomp @SubscribeMapping(“/user/…”) with User Destination doesn't work

爷,独闯天下 提交于 2020-01-01 08:08:12

问题


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 :)


回答1:


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();
}


来源:https://stackoverflow.com/questions/25928047/spring-stomp-subscribemapping-user-with-user-destination-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!