package com.sinata.zuul.util.echo;
|
|
import io.netty.channel.ChannelHandlerContext;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.Set;
|
import java.util.concurrent.ConcurrentHashMap;
|
|
public class NettyChannelMap {
|
|
protected static Map<String, ChannelHandlerContext> map = new ConcurrentHashMap<>();
|
|
public static Map<String, ChannelHandlerContext> ctxMap = new HashMap<>();//单点登录存储的通道
|
|
|
private NettyChannelMap() {
|
// 放置外部实例化
|
}
|
|
/**
|
* Get data from source.
|
*
|
* @param key
|
* @return
|
*/
|
public static ChannelHandlerContext getData(String key) {
|
if(map==null){
|
map = new HashMap<String, ChannelHandlerContext>();
|
}
|
return map.get(key);
|
}
|
|
|
public static ChannelHandlerContext getData_(String key) {
|
if(ctxMap==null){
|
ctxMap = new HashMap<String, ChannelHandlerContext>();
|
}
|
return ctxMap.get(key);
|
}
|
|
|
/**
|
* Save data from source.
|
*
|
* @param key
|
* @param val
|
*/
|
public static synchronized void saveData(String key, ChannelHandlerContext val) {
|
map.put(key, val);
|
}
|
|
/**
|
* Determine whether the cache key contains the key.
|
*
|
* @param key
|
* @return true|false
|
* @author TaoNingBo
|
*/
|
public static synchronized boolean containsKey(String key) {
|
return map.containsKey(key);
|
}
|
|
/**
|
* Determine whether the cache value contains the value.
|
*
|
* @param val
|
* @return
|
*/
|
public static synchronized boolean containsVal(ChannelHandlerContext val) {
|
return map.containsValue(val);
|
}
|
|
/**
|
* Remove the data resources.
|
*
|
* @param value
|
*/
|
@SuppressWarnings("rawtypes")
|
public static synchronized void remove(ChannelHandlerContext value) {
|
Set<String> strings = map.keySet();
|
for(String key : strings){
|
ChannelHandlerContext channelHandlerContext = map.get(key);
|
String s = channelHandlerContext.channel().remoteAddress().toString();
|
String s1 = value.channel().remoteAddress().toString();
|
if(s.equals(s1)){
|
channelHandlerContext.close();//关闭通道
|
map.remove(key);
|
}
|
}
|
}
|
|
|
public static synchronized void remove_(ChannelHandlerContext value) {
|
Set<String> strings = ctxMap.keySet();
|
for(String key : strings){
|
ChannelHandlerContext channelHandlerContext = ctxMap.get(key);
|
String s = channelHandlerContext.channel().remoteAddress().toString();
|
String s1 = value.channel().remoteAddress().toString();
|
if(s.equals(s1)){
|
channelHandlerContext.close();//关闭通道
|
ctxMap.remove(key);
|
}
|
}
|
}
|
|
|
/**
|
* Remove the data resources.
|
*
|
* @param key
|
* @author TaoNingBo
|
*/
|
public static synchronized void remove(String key) {
|
map.remove(key);
|
}
|
|
/**
|
* Update the data resources.
|
*
|
* @param key
|
* @param value
|
*/
|
public static synchronized void update(String key, ChannelHandlerContext value) {
|
map.put(key, value);
|
}
|
|
|
|
public static synchronized void update_(String key, ChannelHandlerContext value) {
|
ctxMap.put(key, value);
|
}
|
}
|