所以我想出了自己。
我的通知有一個收件人ID(用戶ID在通知需要被髮送到)
所以我要發送到「/ WS-用戶/」 + ID +「/問候」,其中id是登錄的用戶。
在客戶端,這很容易實現。
var stompClient = null;
// init
function init() {
/**
* Note that you need to specify your ip somewhere globally
**/
var socket = new SockJS('http://127.0.0.1:9080/ws-notification');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
/**
* This is where I get the id of the logged in user
**/
barService.currentBarAccountStore.getValue().then(function (barAccount) {
subscribeWithId(stompClient,barAccount.user.id);
});
});
}
/**
* subscribe at the url with the userid
**/
function subscribeWithId(stompClient,id){
stompClient.subscribe('/ws-user/'+id+'/greetings', function(){
showNotify();
});
}
/**
* Broadcast over the rootscope to update the angular view
**/
function showNotify(){
$rootScope.$broadcast('new-notification');
}
function disconnect() {
if (stompClient != null) {
stompClient.disconnect();
}
// setConnected(false);
console.log("Disconnected");
}
接下來,我們添加「setUserDestinationPrefix」到MessageBrokerRegistry在WebSocketConfig.java類:
@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調用來訪問我的controllermethod發送了通知訂閱的客戶端。這是由一個事件Consumer類做(問問看代碼,它只是觸發控制器功能,可以做不同的)
@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!"));
}
請檢閱我的代碼,如果你看到任何問題和/或安全問題警告我。
您是否真的花時間閱讀[參考指南](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/websocket.html#websocket-server-handshake )? –
我做過了,正如我所說的那樣,所有這些都是壓倒性的,因此我認爲一個簡單而普遍的答案對於像我這樣的新學習者來說可能非常有用。 – Sytham