|
@@ -1,6 +1,7 @@
|
|
|
package com.ozs.web.controller.websocket;
|
|
|
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.scheduling.annotation.Scheduled;
|
|
|
import org.springframework.stereotype.Component;
|
|
|
|
|
|
import javax.websocket.*;
|
|
@@ -76,6 +77,7 @@ public class WebSocketServer {
|
|
|
System.out.println("链接失败" + webSockets.size());
|
|
|
log.info("【websocket消息】连接断开,总数为:" + webSockets.size());
|
|
|
} catch (Exception e) {
|
|
|
+ log.error("onClose移除连接失败", e);
|
|
|
}
|
|
|
}
|
|
|
|
|
@@ -87,6 +89,8 @@ public class WebSocketServer {
|
|
|
@OnMessage
|
|
|
public void onMessage(String message) {
|
|
|
log.info("【websocket消息】收到客户端消息:" + message);
|
|
|
+ log.info("【收到消息】userId: {}, Session是否打开: {}, 当前webSockets大小: {}",
|
|
|
+ this.userId, this.session.isOpen(), webSockets.size());
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -145,4 +149,17 @@ public class WebSocketServer {
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
+
|
|
|
+ @Scheduled(fixedRate = 30000) // 每30秒执行一次
|
|
|
+ public void cleanInvalidSessions() {
|
|
|
+ List<String> invalidUserIds = sessionPool.entrySet().stream()
|
|
|
+ .filter(entry -> !entry.getValue().isOpen())
|
|
|
+ .map(Map.Entry::getKey)
|
|
|
+ .collect(Collectors.toList());
|
|
|
+ invalidUserIds.forEach(userId -> {
|
|
|
+ sessionPool.remove(userId);
|
|
|
+ webSockets.removeIf(ws -> ws.userId.equals(userId));
|
|
|
+ });
|
|
|
+ log.info("清理无效连接,剩余总数: {}", webSockets.size());
|
|
|
+ }
|
|
|
}
|