All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gateway.connector.tcp.server.TopicManager Maven / Gradle / Ivy

package com.gateway.connector.tcp.server;

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.connector.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;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy