问题
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