所以我自己弄明白了。
我的通知有一个接收者id(通知需要发送到的用户id)
因此,我要发送到“/ws-user/+id+/greetings”,其中id是已登录的用户。
在客户端,这相当容易实现。
var stompClient = null;
function init() {
var socket = new SockJS('http://127.0.0.1:9080/ws-notification');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
barService.currentBarAccountStore.getValue().then(function (barAccount) {
subscribeWithId(stompClient,barAccount.user.id);
});
});
}
function subscribeWithId(stompClient,id){
stompClient.subscribe('/ws-user/'+id+'/greetings', function(){
showNotify();
});
}
function showNotify(){
$rootScope.$broadcast('new-notification');
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
console.log("Disconnected");
}
接下来,在WebSocketConfig.java类的MessageBrokerRegistry中添加“setUserDestinationPrefix”:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
private final static String userDestinationPrefix = "/ws-user/";
@Override
public void configureMessageBroker(MessageBrokerRegistry config){
config.enableSimpleBroker("/ws-topic","/ws-user");
config.setApplicationDestinationPrefixes("/ws-app");
config.setUserDestinationPrefix(userDestinationPrefix);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-notification").setAllowedOrigins("*").withSockJS();
}
}
请注意,我正在使用内部的RestTemplate调用来访问我的控制器方法,该方法向已订阅的客户端发送通知。这是通过一个事件消费者类完成的(如果需要代码,请请求查看,它只是用来触发控制器函数的,可以以不同的方式完成)。
@RequestMapping(value = "/test-notification", method = RequestMethod.POST)
public void testNotification(@RequestBody String recipientId) throws InterruptedException {
this.template.convertAndSendToUser(recipientId,"/greetings", new Notify("ALERT: There is a new notification for you!"));
}
请查看我的代码,如果您发现任何问题和/或安全问题,请告诉我。