package com.jsowell.common.util; import io.netty.channel.ChannelHandlerContext; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; import java.util.concurrent.ConcurrentHashMap; /** * 管理一个全局map,保存连接进服务端的通道数量 */ @Slf4j public class ChannelManagerUtil { // 使用 ConcurrentHashMap 来保证线程安全 private static final ConcurrentHashMap channelMap = new ConcurrentHashMap<>(); /** * 添加通道到 map 中 * * @param channelId 通道 ID * @param ctx 连接的 Channel 对象 */ public static void addChannel(String channelId, ChannelHandlerContext ctx) { if (channelMap.containsKey(channelId)) { log.info("客户端【{}】是连接状态,连接通道数量: {}", channelId, channelMap.size()); } else { channelMap.put(channelId, ctx); InetSocketAddress socket = (InetSocketAddress) ctx.channel().remoteAddress(); String clientIp = socket.getAddress().getHostAddress(); int clientPort = socket.getPort(); log.info("客户端【{}】, 连接netty服务器【IP:{}, PORT:{}】, 连接通道数量: {}", channelId, clientIp, clientPort, channelMap.size()); } } /** * 移除指定的通道 * * @param channelId 通道 ID */ public static void removeChannel(String channelId) { if (!channelMap.containsKey(channelId)) { return; } channelMap.remove(channelId); } /** * 获取当前连接的通道数量 * * @return 通道数量 */ public static int getChannelCount() { return channelMap.size(); } /** * 根据通道 ID 获取 Channel 对象 * * @param channelId 通道 ID * @return Channel 对象或 null 如果不存在 */ public static ChannelHandlerContext getChannel(String channelId) { return channelMap.get(channelId); } }