##策略模板模式,模板方法,高内聚,低耦合
1.背景:消息处理机制,每个消息处理机制一个handler,代码冗余,难维护。
2.实现:
1.首先定义一个带有泛型的接口,一个抽象类实现这个接口,抽象类里面方法的入参可以是具体的泛型
2.static方法,里面根据抽象类的类对象获取一个类列表,可以排序AnnotationAwareOrderComparator
3.抽象类里面match方法,match公共的参数,match到了,每个handler自己的domatch
,domatch==true,抽象类里面的deal方法执行,之后执行每个handler的dodeal方法执行
3.代码
public interface ConsumerMQInterface<T> {
public boolean match(T t);
public void deal(T t);
}
@Service
public abstract class ConsumerMQAbstractService implements ConsumerMQInterface<RocketMessageExt<Map<String, Object>>> {
@Override
public boolean match(RocketMessageExt<Map<String, Object>> map) {
// common deal
return this.doMatch(map);
}
@Override
public void deal(RocketMessageExt<Map<String, Object>> map) {
// common deal
this.doDeal(map);
}
protected abstract boolean doMatch(RocketMessageExt<Map<String, Object>> map);
protected abstract void doDeal(RocketMessageExt<Map<String, Object>> map);
}
public class ConsumerMQ implements MessageHandler<Map<String, Object>> {
private static Logger logger = LoggerFactory.getLogger(ConsumerMQ.class);
private static List<ConsumerMQInterface<RocketMessageExt<Map<String, Object>>>> handlerList = new ArrayList<ConsumerMQInterface<RocketMessageExt<Map<String, Object>>>>();
@Override
public void onMessage(List<RocketMessageExt<Map<String, Object>>> list, Object o) {
for (RocketMessageExt<Map<String, Object>> messageExt : list) {
logger.info("keys:{} Message:{}", messageExt.getKeys(), messageExt.getBody());//map
for (ConsumerMQInterface<RocketMessageExt<Map<String, Object>>> handler : handlerList) {
if (handler.match(messageExt)) {
handler.deal(messageExt);
}
}
}
}
static {
Map<String, ConsumerMQAbstractService> handlerMap = ApplicationContextUtil.getBeansOfType(ConsumerMQAbstractService.class);
handlerList.addAll(handlerMap.values());
Collections.sort(handlerList, AnnotationAwareOrderComparator.INSTANCE);
}
}
@Service
public class MqDelayMessageRocketMqHandler extends ConsumerMQAbstractService {
@Override
protected boolean doMatch(RocketMessageExt<Map<String, Object>> map) {
if (筛选) {
return true;
}
return false;
}
@Override
protected void doDeal(RocketMessageExt<Map<String, Object>> rocketmap) {
//实现
}
}
@Component
@Lazy(value = false)
public class ApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context = null;
private ApplicationContextUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContextUtil getInstance() {
return (ApplicationContextUtil)context.getBean("applicationContextUtil");
}
public static Object getBean(String name){
return context.getBean(name);
}
public static Object getBean(Class classz){
return context.getBean(classz);
}
public static <T> Map<String, T> getBeansOfType(Class<T> clazz) {
Map<String, T> beansOfType = context.getBeansOfType(clazz);
return beansOfType;
}
}