package com.casic.missiles.netty; import cn.hutool.core.util.ObjectUtil; import io.netty.channel.Channel; import io.netty.util.AttributeKey; import org.springframework.stereotype.Component; import java.util.concurrent.ConcurrentHashMap; @Component public class ChannelCache { // 存储用户id和Channel.id().asLongText()对应关系 private static final ConcurrentHashMap<String, Channel> channelMap = new ConcurrentHashMap<String, Channel>(); // 存储用户id和Channel.id().asLongText()对应关系 private static final ConcurrentHashMap<String, String> channelIdUid = new ConcurrentHashMap<String, String>(); private static final AttributeKey<String> CHANNEL_ATTR_KEY = AttributeKey.valueOf("user"); public ConcurrentHashMap<String, String> getChannelIdUid() { return channelIdUid; } /** * 获取Channel * * @return */ /** * 添加Channel到ChannelGroup * * @param uid * @param channel */ public synchronized void addChannel(Channel channel, String uid) { channel.attr(CHANNEL_ATTR_KEY).set(uid); Channel channel_ = channelMap.get(channel.id().asLongText()); if (channel_ == null) { channelMap.put(channel.id().asLongText(), channel); } channelIdUid.put(uid, channel.id().asLongText()); } /** * 删除Channel * * @param channel */ public synchronized void removeChannel(Channel channel) { Channel channel_ = channelMap.get(channel.id().asLongText()); if (channel_ != null) { channelMap.remove(channel.id().asLongText()); } String userId = channel.attr(CHANNEL_ATTR_KEY).get(); if (userId != null) { channelIdUid.remove(userId); } } /** * 获取Channel * * @return */ /** * 根据用户id获取该用户的通道 * * @param userId * @return */ public synchronized Channel getChannelByUserId(String userId) { String channelIdStr = channelIdUid.get(userId); if (ObjectUtil.isNotEmpty(channelIdStr)) { return channelMap.get(channelIdStr); } return null; } /** * 根据channel获取userId * * @param channel */ public synchronized String getUserId(Channel channel) { String userId = channel.attr(CHANNEL_ATTR_KEY).get(); return userId; } }