package com.tongran.agenttcp.server.basics; import com.tongran.agenttcp.server.annotation.AgentDispatcher; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; import org.springframework.util.CollectionUtils; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Component public class AgentDispatcherManager implements ApplicationContextAware { /** * 所有实现的包处理器 */ private static Map MSG_HANDLER_MAP; /** * 唤醒时 初始化 packHandlerMap */ @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // 仅一次性初始化完成 if (MSG_HANDLER_MAP == null) { MSG_HANDLER_MAP = new ConcurrentHashMap<>(); Map handlers = applicationContext.getBeansWithAnnotation(AgentDispatcher.class); if (!CollectionUtils.isEmpty(handlers)) { handlers.values().forEach(tempHandler -> { boolean result = tempHandler.getClass().isAnnotationPresent(AgentDispatcher.class); if (result) { AgentDispatcher annotation = tempHandler.getClass().getAnnotation(AgentDispatcher.class); MSG_HANDLER_MAP.put(annotation.msgId().getValue() + "&" + annotation.version().value, (AgentMsgHandler) tempHandler); } }); } } } public AgentMsgHandler getHandler(String msgIdVersion) { return MSG_HANDLER_MAP == null ? null : MSG_HANDLER_MAP.get(msgIdVersion); } }