在Spring Boot Websocket中向特定用户发送通知
我想向特定客户发送通知。
例如用户名user
@Configuration@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends
AbstractWebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
stompEndpointRegistry.addEndpoint("/socket")
.setAllowedOrigins("*")
.withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/topic", "/queue");
registry.setApplicationDestinationPrefixes("/app");
}
@GetMapping("/notify")public String getNotification(Principal principal) {
String username = "user";
notifications.increment();
logger.info("counter" + notifications.getCount() + "" + principal.getName());
// logger.info("usersend:"+sha.getUser().getName()) ; //user
template.convertAndSendToUser(principal.getName(), "queue/notification", notifications);
return "Notifications successfully sent to Angular !";
}
角度服务
connect() { let socket = new SockJs(`api/socket`);
let stompClient = Stomp.over(socket);
return stompClient;
}
角分量
let stompClient = this.webSocketService.connect(); stompClient.connect({}, frame => {
stompClient.subscribe('/user/queue/notification', notifications => {
console.log('test'+notifications)
this.notifications = JSON.parse(notifications.body).count;
}) });
Opening Web Socket... stomp.js:134 Web Socket Opened...
stomp.js:134 >>> CONNECT
accept-version:1.1,1.0
heart-beat:10000,10000
stomp.js:134 <<< CONNECTED
version:1.1
heart-beat:0,0
stomp.js:134 connected to server undefined
reminder.component.ts:18 test callsed
stomp.js:134 >>> SUBSCRIBE
id:sub-0
destination:/user/queue/notification
提前致谢 。
回答:
gerrytan对在SpringWebsocket上向特定用户发送消的回答提到了Web套接字配置更改,以注册/user
前缀。就您而言,我想这意味着要更换
registry.enableSimpleBroker("/topic", "/queue");
与
registry.enableSimpleBroker("/topic", "/queue", "/user");
他还说,在控制器中,您不需要/user
前缀,因为它是自动添加的。因此,您可以尝试以下操作:
template.convertAndSendToUser(principal.getName(), "/queue/notification", notifications);
和这个:
template.convertAndSendToUser(principal.getName(), "/user/queue/notification", notifications);
在客户端,您需要提供用于连接服务器的用户名。您可以直接将其插入:
stompClient.subscribe('/user/naila/queue/notification', ...)
或从标题获取它。但是马库斯在“如何向特定用户发送网络套接字消息”中)说?即使在这里您也不需要用户名,因此它可能像这样工作:
stompClient.subscribe('/user/queue/notification', ...)
以上是 在Spring Boot Websocket中向特定用户发送通知 的全部内容, 来源链接: utcz.com/qa/421651.html