liusuyi
2025-10-30 9f911c1461ba33c1a561046eb1ac8e1c56fc9b9d
ard-work/src/main/java/com/ard/work/component/netty/TyTcpClientManager.java
@@ -6,6 +6,7 @@
import com.ard.work.component.netty.handler.MessageProtocolEncoder;
import com.ard.work.component.netty.cache.TyTcpServerCache;
import com.ard.work.domain.entity.ArdServerInfo;
import com.ard.work.service.IArdDroneInfoService;
import com.ard.work.service.IArdServerInfoService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
@@ -32,6 +33,9 @@
    @Resource
    private IArdServerInfoService ardServerService; // ← 从数据库读取边缘服务器配置
    @Resource
    private IArdDroneInfoService ardDroneService;
    @Resource
    private ClientHandler clientHandler;
@@ -76,8 +80,8 @@
                Channel channel = f.channel();
                channel.attr(AttributeKey.valueOf("serverId")).set(serverId);
                TyTcpServerCache.putTcpServerCache(serverId, true);
                // 断开服务器,修改状态为: 0 - 在线
                ardServerService.updateServerStatus(serverId, "1");
                // 修改状态为: 1 - 在线
                updateServerAndDroneStatus(serverId, "1");
                // 成功后再加入 channels
                TyTcpServerCache.putChannel(serverId, channel);
@@ -86,7 +90,7 @@
                log.warn("❌ 服务器 [{}] 连接失败", serverId);
                TyTcpServerCache.putTcpServerCache(serverId, false);
                // 断开服务器,修改状态为: 0 - 离线
                ardServerService.updateServerStatus(serverId, "0");
                updateServerAndDroneStatus(serverId, "0");
            }
        });
    }
@@ -100,12 +104,19 @@
            channel.close();
            log.info("断开服务器 [{}] 连接", serverId);
            // 断开服务器,修改状态为: 0 - 离线
            ardServerService.updateServerStatus(serverId, "0");
            updateServerAndDroneStatus(serverId, "0");
            TyTcpServerCache.removeChannel(serverId);
        }
        TyTcpServerCache.removeTcpServerCache(serverId);
    }
    /**
     * 同步修改服务和无人机状态
     */
    private void updateServerAndDroneStatus(String serverId, String status) {
        ardServerService.updateServerStatus(serverId, status);
        ardDroneService.updateDroneStatus(serverId, status);
    }
    /**
     * 启动时从数据库加载所有边缘服务器并建立 TCP 连接
@@ -113,7 +124,7 @@
    @PostConstruct
    public void initConnectServers() {
        try {
            var serverList = ardServerService.selectArdServerInfoList(new ArdServerInfo()); // ← 从数据库查询所有服务器配置
            var serverList = ardServerService.selectArdServerInfoList(new ArdServerInfo() {{ setUseDataScope(false); }}); // ← 从数据库查询所有服务器配置
            if (serverList == null || serverList.isEmpty()) {
                log.warn("未在数据库中找到边缘服务器配置,跳过连接初始化");
                return;