【发布时间】:2017-01-25 13:41:52
【问题描述】:
我有这个代码:使用 javascript 的客户端:
socket = new SockJS(context.backend + '/myWebSocketEndPoint');
stompClient = Stomp.over(socket);
stompClient.connect({},function (frame) {
stompClient.subscribe('/queue/'+clientId+'/notification', function(response){
alert(angular.fromJson(response.body));
});
});
在此代码中,客户端在连接时,使用'/queue/'+他的客户端ID +'/notification/订阅接收通知。所以我为每个客户排队。我将 stomp 与 sockjs 一起使用
在我的服务器(Java + spring boot)中,我有一个通知侦听器,当事件发布时,它会向所有客户端发送通知。所以我有:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/queue");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/myWebSocketEndPoint")
.setAllowedOrigins("*")
.withSockJS();
}
}
调用 MenuItemNotificationSender 向用户发送通知的类 MenuItemNotificationChannel。
@Component
public class MenuItemNotificationChannel extends AbstractNotificationChannel {
@Autowired
private MenuItemNotificationSender menuItemNotificationSender;
@Autowired
private UserRepository userRepository;
@Override
public void sendNotification(KitaiEvent<?> event, Map<String, Object> notificationConfiguration) throws Exception {
String menuItem = Optional.ofNullable((String) notificationConfiguration.get(MENU_ENTRY_KEY)).orElseThrow(IllegalArgumentException::new);
List<User> userList = userRepository.findAll();
for(User u: userList){
menuItemNotificationSender.sendNotification(new MenuItemDto(menuItem),u.getId());
}
MenuItemNotificationSender 类是:
@Component
public class MenuItemNotificationSender {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Autowired
public MenuItemNotificationSender(SimpMessagingTemplate messagingTemplate){
this.messagingTemplate = messagingTemplate;
}
public void sendNotification(MenuItemDto menuItem,Long id) {
String address = "/queue/"+id+"/notification";
messagingTemplate.convertAndSend(address, menuItem);
}
}
此代码完美运行:通知会发送给每个用户。但是如果用户不在线,通知就会丢失。我的问题是:
我如何验证哪些订阅有效,哪些订阅无效? (如果我可以验证订阅是否处于活动状态,我会解决我的问题,因为我会离线保存用户通知,然后在他们登录时发送)
我可以使用持久队列吗? (我读过一些关于它的东西,但我不明白我是否只能将它与 stomp 和 sockjs 一起使用)
对不起我的英语! :D
【问题讨论】:
标签: spring websocket queue subscription stomp