com.gateway.invoke.TopicManager Maven / Gradle / Ivy
package com.gateway.invoke;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gateway.utils.TopicUtils;
/**
* topic<->session管理
*
* @author deshuai.kong
*
*/
public class TopicManager {
private final static Logger logger = LoggerFactory.getLogger(TopicManager.class);
private ConcurrentHashMap> topicHm = new ConcurrentHashMap>();
private ConcurrentHashMap> topicWildCardHm = new ConcurrentHashMap>();
public ConcurrentHashMap> getTopics() {
return topicHm;
}
public ConcurrentHashMap> getTopicsWildCard() {
return topicWildCardHm;
}
public synchronized boolean add(String sessionid, String topic) {// 添加
boolean flag = false;
if (StringUtils.isNoneEmpty(sessionid)) {
CopyOnWriteArraySet cas = null;
boolean isWildcard = TopicUtils.isWildcard(topic);
if (!isWildcard) {
cas = topicHm.get(sessionid);
if (cas == null) {
cas = new CopyOnWriteArraySet();
topicHm.put(sessionid, cas);
}
} else {
cas = topicWildCardHm.get(sessionid);
if (cas == null) {
cas = new CopyOnWriteArraySet();
topicWildCardHm.put(sessionid, cas);
}
}
CopyOnWriteArraySet tmpWildCard = topicWildCardHm.get(sessionid);
CopyOnWriteArraySet tmp = topicHm.get(sessionid);
if (tmpWildCard != null) {
for (String stopic : tmpWildCard) {
if (TopicUtils.matchTopic(stopic, topic)) {
logger.warn("topic:{} match topic:{},so drop,sessionid:{} from sessions", topic, stopic,
sessionid);
flag = true;
}
}
if (!flag && tmp != null) {
if (tmp.contains(topic)) {
logger.warn("topic:{} duplicate:{},so drop,sessionid:{} from sessions", topic, sessionid);
flag = true;
}
}
}
if (!flag) {
logger.warn("add topic:{},sessionid:{} from sessions", topic, sessionid);
cas.add(topic);
flag = true;
}
}
return flag;
}
public synchronized boolean remove(String sessionid, String topic) {// 删除
boolean flag = true;
CopyOnWriteArraySet cas = null;
boolean isWildcard = TopicUtils.isWildcard(topic);
if (!isWildcard) {
cas = topicHm.get(sessionid);
} else {
cas = topicWildCardHm.get(sessionid);
}
if (cas != null) {
cas.remove(topic);
logger.warn("remove topic:{},sessionid:{} from sessions", topic, sessionid);
}
return flag;
}
public synchronized boolean clear(String sessionid) {// 清除topic
boolean flag = false;
topicHm.remove(sessionid);
topicWildCardHm.remove(sessionid);
logger.warn("clear topic " + sessionid + " from sessions!");
flag = true;
return flag;
}
}