|
@@ -2,14 +2,20 @@ package com.sikey.wa04.business.application.service.websocket;
|
|
|
|
|
|
import com.sikey.wa04.business.application.converter.ConnectionConverter;
|
|
|
import com.sikey.wa04.business.domain.entity.websocket.Connection;
|
|
|
+import com.sikey.wa04.business.domain.entity.websocket.ConnectionId;
|
|
|
import com.sikey.wa04.business.infrastructure.adapter.CacheConnectionStateManager;
|
|
|
import com.sikey.wa04.business.infrastructure.adapter.RedisConnectionStateManager;
|
|
|
+import com.sikey.wa04.business.infrastructure.configuration.WebSocketConfig;
|
|
|
import jakarta.annotation.Resource;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.beans.factory.annotation.Autowired;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
import org.springframework.web.socket.CloseStatus;
|
|
|
import org.springframework.web.socket.WebSocketSession;
|
|
|
|
|
|
+import java.time.Duration;
|
|
|
+import java.util.List;
|
|
|
+
|
|
|
/**
|
|
|
* 连接管理
|
|
|
*
|
|
@@ -25,6 +31,13 @@ public class ConnectionManagerService {
|
|
|
@Resource
|
|
|
private CacheConnectionStateManager cacheConnectionStateManager;
|
|
|
|
|
|
+ private WebSocketConfig webSocketConfig;
|
|
|
+
|
|
|
+ @Autowired
|
|
|
+ public void setWebSocketConfig(WebSocketConfig webSocketConfig) {
|
|
|
+ this.webSocketConfig = webSocketConfig;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 连接建立
|
|
|
*/
|
|
@@ -42,8 +55,24 @@ public class ConnectionManagerService {
|
|
|
public void connectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) {
|
|
|
log.info("Connection closed code: {}", closeStatus.getCode());
|
|
|
|
|
|
- Connection connection = ConnectionConverter.to(webSocketSession);
|
|
|
+ ConnectionId connectionId = ConnectionConverter.toConnectionId(webSocketSession);
|
|
|
+ Connection connection = cacheConnectionStateManager.getConnection(connectionId);
|
|
|
cacheConnectionStateManager.offline(connection);
|
|
|
redisConnectionStateManager.offline(connection);
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 移除死连接
|
|
|
+ */
|
|
|
+ public void removeDeadConnection() {
|
|
|
+ log.info("Remove dead connection");
|
|
|
+
|
|
|
+ List<Connection> connections = cacheConnectionStateManager.getConnections();
|
|
|
+ for (Connection connection : connections) {
|
|
|
+ if (connection.isDead(Duration.ofSeconds(webSocketConfig.getHeartbeatTimeout()))) {
|
|
|
+ cacheConnectionStateManager.offline(connection);
|
|
|
+ redisConnectionStateManager.offline(connection);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|