From 115a5bc6504ff1a1dd7f9acd93d2df1cfaee2ba7 Mon Sep 17 00:00:00 2001 From: gsd Date: Sat, 3 Feb 2024 22:32:49 +0300 Subject: [PATCH] external services fix 2 --- src/main/java/app/services/ExternalServices.java | 4 ++++ .../handlers/ExternalServicesHandler.java | 14 +++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/main/java/app/services/ExternalServices.java b/src/main/java/app/services/ExternalServices.java index 5727b56..e1900a7 100644 --- a/src/main/java/app/services/ExternalServices.java +++ b/src/main/java/app/services/ExternalServices.java @@ -51,4 +51,8 @@ public class ExternalServices { if (name == null || name.isEmpty()) return; services.put(name, Instant.now().getEpochSecond()); } + + public void inactive(String name) { + services.put(name, 0L); + } } diff --git a/src/main/java/app/websocket/handlers/ExternalServicesHandler.java b/src/main/java/app/websocket/handlers/ExternalServicesHandler.java index 1118d72..4f36c1f 100644 --- a/src/main/java/app/websocket/handlers/ExternalServicesHandler.java +++ b/src/main/java/app/websocket/handlers/ExternalServicesHandler.java @@ -15,13 +15,15 @@ import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.util.HashMap; +import java.util.Map; @Component public class ExternalServicesHandler extends TextWebSocketHandler implements BaseWebsocketHandler { private final Logger logger = LoggerFactory.getLogger(getClass()); private ObjectMapper objectMapper = new ObjectMapper(); - + private final Map activeSessions = new HashMap<>(); + private final Map nameSessions = new HashMap<>(); private ExternalServices externalServices; @Autowired @@ -40,6 +42,7 @@ public class ExternalServicesHandler extends TextWebSocketHandler implements Bas super.afterConnectionEstablished(session); if (session.isOpen()) { logger.info("Session {} open", session.getId()); + activeSessions.put(session.getId(), session); } } @@ -55,12 +58,21 @@ public class ExternalServicesHandler extends TextWebSocketHandler implements Bas return; } String service_name = (String) payload.get("name"); + if (service_name == null || service_name.isEmpty()) return; + nameSessions.put(session.getId(), service_name); externalServices.update(service_name); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { logger.info("Session {} close", session.getId()); + if (activeSessions.containsKey(session.getId())) { + activeSessions.remove(session.getId()); + } + if (nameSessions.containsKey(session.getId())) { + externalServices.inactive(nameSessions.get(session.getId())); + nameSessions.remove(session.getId()); + } super.afterConnectionClosed(session, status); } }