Browse Source

fix : Websocket增加心跳机制

bilingfeng 1 year ago
parent
commit
eefe510682

+ 1 - 1
game-module/game-module-manage/src/main/java/com/zanxiang/game/module/manage/ManageApplication.java

@@ -23,7 +23,7 @@ public class ManageApplication {
 
     public static void main(String[] args) {
         SpringApplication.run(ManageApplication.class, args);
-        System.out.println("赞象Manage服务启动成功 <Websocket代码优化> ( ´・・)ノ(._.`) \n" +
+        System.out.println("赞象Manage服务启动成功 <Websocket增加心跳机制> ( ´・・)ノ(._.`) \n" +
                 "___  ___  ___   _   _   ___  _____  _____ \n" +
                 "|  \\/  | / _ \\ | \\ | | / _ \\|  __ \\|  ___|\n" +
                 "| .  . |/ /_\\ \\|  \\| |/ /_\\ \\ |  \\/| |__  \n" +

+ 56 - 0
game-module/game-module-manage/src/main/java/com/zanxiang/game/module/manage/websocket/KfMsgWebsocketHeartbeat.java

@@ -0,0 +1,56 @@
+package com.zanxiang.game.module.manage.websocket;
+
+import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
+import com.zanxiang.game.module.manage.enums.KfWebSocketMsgEnum;
+import com.zanxiang.game.module.manage.pojo.dto.KfWebSocketMsgDTO;
+import com.zanxiang.module.util.JsonUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+import org.springframework.web.socket.TextMessage;
+import org.springframework.web.socket.WebSocketSession;
+
+import java.util.List;
+
+/**
+ * @author : lingfeng
+ * @time : 2024-03-05
+ * @description : Websocket心跳
+ */
+@Slf4j
+@Component
+public class KfMsgWebsocketHeartbeat {
+
+    @Autowired
+    private KfMsgWebSocketSessionRegistry kfMsgWebSocketSessionRegistry;
+
+    /**
+     * Websocket每20秒给客户端发送一次心跳
+     */
+    @Scheduled(cron = "0/20 * * * * ? *")
+    public void sessionHeartbeat() {
+        List<WebSocketSession> sessionList = kfMsgWebSocketSessionRegistry.getAllSessions();
+        if (CollectionUtils.isEmpty(sessionList)) {
+            return;
+        }
+        sessionList.forEach(this::sendHeartbeat);
+    }
+
+    private void sendHeartbeat(WebSocketSession session) {
+        //会话不存在或者未开启
+        if (session == null || !session.isOpen()) {
+            return;
+        }
+        Object kfUserId = session.getAttributes().get("kfUserId");
+        KfWebSocketMsgDTO webSocketMsgDTO = KfWebSocketMsgDTO.builder()
+                .webSocketMsgType(KfWebSocketMsgEnum.WEBSOCKET_MSG_CONNECT_HEART_BEAT)
+                .kfUserId(kfUserId == null ? null : Long.valueOf(kfUserId.toString()))
+                .build();
+        try {
+            session.sendMessage(new TextMessage(JsonUtil.toString(webSocketMsgDTO)));
+        } catch (Exception e) {
+            log.error("给客户端发送心跳消息异常, kfUserId : {}, e : {}", JsonUtil.toString(kfUserId), e.getMessage());
+        }
+    }
+}