添加测试handler
一:定义上传json,注意,mId是必须的。
1 { 2 "mId": 101, 3 "name":"cddd", 4 "age":23 5 }
二:新建上传json解析类,继承上传抽象类AbstractUpMessage。
public class DemoRequest extends AbstractUpMessage { public String name; public int age; @Override protected void decodeBody() { name = bodyData.getString("name",""); age = bodyData.getInteger("age",0); } }
三:定义返回json
{ "mId": 101, "code": 200, "name":"res", "info":"ininii" }
四:定义返回编码类,继承AbstractDownMessage
public class DemoResponse extends AbstractDownMessage { private String name; private String info; public DemoResponse(short mId,String name,String info){ messageId = mId; this.name = name; this.info = info; } @Override protected void encodeBody() { bodyData.put("name",name); bodyData.put("info",info); } }
五,定义handler,实现接口 InterHandler
1 public class DemoHandler implements InterHandler { 2 @Override 3 public void handler(AbstractUpMessage up, HttpServerResponse resp) { 4 //上传参数 5 DemoRequest request = (DemoRequest)up; 6 System.out.println("上传参数:"+ request.name + "-" + request.age); 7 8 //返回数据 9 String n = "cscscs---"; 10 String in = "info ---"; 11 //编码返回json 12 DemoResponse response = new DemoResponse(getMessageId(),n,in); 13 response.encode(); 14 resp.end(response.SendMessage()); 15 } 16 17 @Override 18 public short getMessageId() { 19 return HandlerCode.DEMO_V1; 20 } 21 }
六:加载handler。定义一个配置类Configure,初始化handler
public class Configure { private static final Configure ourInstance = new Configure(); public static Configure getInstance() { return ourInstance; } public void init(){ initHandler(); } private void initHandler(){ HandlerManager.getInstance().addHandler(new DemoHandler()); } }
修改OnlineServer主函数,加载configure。
public static void main(String[] args){ Configure.getInstance().init(); VertxOptions vertxOptions = new VertxOptions(); Vertx vertx = Vertx.vertx(vertxOptions); //部署http服务器 vertx.deployVerticle(HttpServerVerticle.class.getName(), new DeploymentOptions().setInstances(VertxOptions.DEFAULT_EVENT_LOOP_POOL_SIZE), res -> { if(res.succeeded()){ logger.warn("服务端部署成功----"); }else { logger.error("服务端部署失败---" + res.cause()); } }); }
七:修改 MessageRecognizer 添加解码json的类
public class MessageRecognizer implements IMessageRecognizer { @Override public MessageFactory recognize(short messageId) { switch (messageId){ case HandlerCode.DEMO_V1: return new DemoRequest(); default:return null; } } }
八:启动服务,调用接口试试
成功!!!!
项目结构: