我为这种情况写了一个解决方法。首先,我为 websockets 事件创建了一个侦听器。在订阅请求的情况下,我将 userId 保留在请求中并保存在 ConcurrentHashMap 中。另一方面,当客户端断开连接或发送取消订阅请求时,我会从该 Map 中删除他的 userId。
我的听众课:
@Service
public class MyEventListener {
@Autowired
private NotificationPublisher notificationPublisher;
@EventListener({SessionSubscribeEvent.class})
public void onWebSocketSubscribeEvent(SessionSubscribeEvent event) {
notificationPublisher.subscribedUsers.put(event.getUser().getName(), Calendar.getInstance().getTimeInMillis());
}
@EventListener({SessionUnsubscribeEvent.class})
public void onWebSocketUnsubscribeEvent(SessionUnsubscribeEvent event) {
notificationPublisher.subscribedUsers.remove(event.getUser().getName());
}
@EventListener({SessionDisconnectEvent.class})
public void onWebSocketDisconnectEvent(SessionDisconnectEvent event) {
notificationPublisher.subscribedUsers.remove(event.getUser().getName());
}
}
实际作业正在运行的通知发布者类:
public class NotificationPublisher {
public final Map<String, Long> subscribedUsers = new ConcurrentHashMap<>();
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Autowired
private MyService myService;
@Value("${task.notifications.publisher.websocket_timeout_seconds}")
private int websocketSessionTimeout;
public void sendDataUpdates() {
SocketResponseCount count = null;
for(String key: subscribedUsers.keySet()) {
long subscribeTime = subscribedUsers.get(key);
if(Calendar.getInstance().getTimeInMillis() - subscribeTime > websocketSessionTimeout*1000) {
subscribedUsers.remove(key);
continue;
}
count = myService.getNotificationsCount(key);
this.messagingTemplate.convertAndSendToUser(key, "/queue/publish",count);
}
}
}
也许它会帮助某人