Vertx 实现webapi实战项目(三)
实现消息分发和handler分配:上传json根据mId字段不同提供不同的解析器,然后将消息分发到不同的handler中。
一:消息分发
1:建立消息解析。新建接口IMessageRecognizer
/*** * 根据mId获取不同的解码器 * ***/ public interface IMessageRecognizer { MessageFactory recognize(short messageId); }
2:实现接口。MessageRecognizer
public class MessageRecognizer implements IMessageRecognizer { @Override public MessageFactory recognize(short messageId) { return null; } }
二:handler管理
1:新建接口InterHandler
public interface InterHandler { void handler(AbstractUpMessage up, HttpServerResponse resp); short getMessageId(); }
2:新建handler管理类,使用Map将handler储存,使用时通过mId获取相应的handler
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class HandlerManager { 2 private final Map<Short,InterHandler> handlers = new ConcurrentHashMap<>(); 3 4 private static HandlerManager ourInstance = new HandlerManager(); 5 6 public static HandlerManager getInstance() { 7 if(ourInstance == null){ 8 synchronized (HandlerManager.class){ 9 ourInstance = new HandlerManager(); 10 } 11 } 12 return ourInstance; 13 } 14 15 public void addHandler(InterHandler handler){ 16 InterHandler old = handlers.putIfAbsent(handler.getMessageId(),handler); 17 if(old != null){ 18 throw new RuntimeException("handler repeat :"+handler.getMessageId()); 19 } 20 } 21 22 public InterHandler getHandler(short code){ 23 return handlers.get(code); 24 } 25 }
下节介绍怎么使用前面建立的类。
项目结构如下,