package com.casic.missiles.netty; import io.netty.channel.Channel; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; import org.springframework.context.annotation.Configuration; import java.util.concurrent.ConcurrentHashMap; @Configuration public class ChannelCache { // 存储所有Channel private ChannelGroup channelGroup = new DefaultChannelGroup("channelGroups", GlobalEventExecutor.INSTANCE); // 存储Channel.id().asLongText()和用户id对应关系 private ConcurrentHashMap<String, Integer> channelIdUid = new ConcurrentHashMap<String, Integer>(); public ChannelGroup getChannelGroup() { return channelGroup; } public ConcurrentHashMap<String, Integer> getChannelIdUid() { return channelIdUid; } /** * 获取Channel * * @return */ public Channel getChannel(Channel channel) { Channel channel_ = channelGroup.find(channel.id()); if (channel_ != null) { return channel_; } return null; } /** * 添加Channel到ChannelGroup * * @param uid * @param channel */ public void addChannel(Channel channel, int uid) { Channel channel_ = channelGroup.find(channel.id()); if (channel_ == null) { channelGroup.add(channel); } // redis添加对应用户和channelId之前的关系 Integer userId = channelIdUid.get(channel.id().asLongText()); channelIdUid.put(channel.id().asLongText(), userId); } /** * 删除Channel * * @param channel */ public void removeChannel(Channel channel) { Channel channel_ = channelGroup.find(channel.id()); if (channel_ != null) { channelGroup.remove(channel_); } Integer userId = channelIdUid.get(channel.id().asLongText()); if (userId != null) { channelIdUid.remove(channel.id().asLongText()); } } }