各位开发者大家好,
我最近实现了 Java Spring WebSockets 以在我的应用程序中发送通知,当我发送给所有用户但不发送给特定用户时,Websocket 通信可与 ConvertAndSend 配合使用
WebSocket 配置(WebSocketBrokerConfiguration.java):
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketBrokerConfiguration implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/notification");
registry.setApplicationDestinationPrefixes("/app");
}
}
安全配置(SecurityConfiguration.java):
.authorizeHttpRequests(authz ->
authz.requestMatchers("*/ws/**").permitAll()
在资源中发送通知:
this.simpMessagingTemplate.convertAndSendToUser(
employee.getEmail(),
"/notification",
new NotificationDTO(
NotificationTypeEnum.NEW_REQUEST,
"A new request has been made"
));
前端实现(Angular - 主要组件):
const stompClient: Client = this.notificationService.connect();
stompClient.connect({}, frame => {
console.log('[Websocket] Connected: ' + frame);
stompClient.subscribe('/user/notification', data => {
console.log('[Websocket] ', data);
});
});
通知服务(角度):
connect(): Client {
const socket = new SockJs('/ws');
const stompClient = Stomp.over(socket);
return stompClient;
}
面临的问题: WebSocket 连接似乎已正确建立,并且订阅已在前端设置。但是,订阅 /user/notification 的员工帐户不会收到使用 ConvertAndSendToUser 发送的通知。
SimpMessagingTemplate#convertAndSendToUser 将在内部添加前缀“/user”(默认用户目标前缀,您可以配置)并将用户名和提供的目标附加到其中,并将其用作消息目标。
因此您必须在客户端中订阅
/user/{employee-email}/notification
。并在您的 simpleBroker 列表中注册 /user
。