package github.javaguide.remoting.transport.netty.client; import io.netty.channel.Channel; import lombok.extern.slf4j.Slf4j; import java.net.InetSocketAddress; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * store and get Channel object * * @author shuang.kou * @createTime 2020年05月29日 16:36:00 */ @Slf4j public class ChannelProvider { private final Map channelMap; public ChannelProvider() { channelMap = new ConcurrentHashMap<>(); } public Channel get(InetSocketAddress inetSocketAddress) { String key = inetSocketAddress.toString(); // determine if there is a connection for the corresponding address if (channelMap.containsKey(key)) { Channel channel = channelMap.get(key); // if so, determine if the connection is available, and if so, get it directly if (channel != null && channel.isActive()) { return channel; } else { channelMap.remove(key); } } return null; } public void set(InetSocketAddress inetSocketAddress, Channel channel) { String key = inetSocketAddress.toString(); channelMap.put(key, channel); } public void remove(InetSocketAddress inetSocketAddress) { String key = inetSocketAddress.toString(); channelMap.remove(key); log.info("Channel map size :[{}]", channelMap.size()); } }