Vertx 实现webapi实战项目(四)

本节主要介绍使用消息解析和handler分发

一:定义一个常量类,储存消息id

public class HandlerCode {
    /***** 测试接口 ******/
    public static final short DAILY_LEVEL = 101;
}

 定义一个返回信息枚举类

 1 public enum HttpStatus {
 2     OK(200, "success"),
 3     PLAYER_REGISTER(201,"head register"),
 4     REDIRECT_LOGIN(202,"remote device login"),
 5 
 6     ERROR(501, "error"),
 7     JSON_ERROR(502,"json error"),
 8     PARAMETER_ERROR(503,"parameter error");
 9     
10     private final int code;
11     private final String message;
12 
13     HttpStatus(int code, String message) {
14         this.code = code;
15         this.message = message;
16     }
17 
18     public int code() {
19         return code;
20     }
21 
22     public String message() {
23         return message;
24     }
25 }
View Code

 

二:新建一个返回错误编码类

 1 public class NetDownError extends AbstractDownMessage {
 2     public NetDownError(short requestId, HttpStatus status){
 3         this.messageId = requestId;
 4         this.resultCode = status.code();
 5     }
 6 
 7     @Override
 8     protected void encodeBody() {
 9 
10     }
11 }
View Code

 

三:修改httpServerVerticle解析消息。红色为修改的地方。

public class HttpServerVerticle extends AbstractVerticle {
    private final Logger logger = LoggerFactory.getLogger(HttpServerVerticle.class);
    private HttpServer httpServer;

    private IMessageRecognizer recognizer;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        recognizer = new MessageRecognizer();

        HttpServerOptions options = new HttpServerOptions()
                .setIdleTimeout(10000)
                .setIdleTimeoutUnit(TimeUnit.MILLISECONDS)
                .setTcpKeepAlive(true);

        httpServer = vertx.createHttpServer(options);
        httpServer.exceptionHandler( it -> {
            if(it instanceof IOException){
                logger.error("\n ---network io error:"+it.getMessage());
                return;
            }
            logger.error("\n ---net error:"+it.getMessage());
        });

//        httpServer.requestHandler(req -> {
//            HttpServerResponse resp = req.response().setStatusCode(200);
//            resp.putHeader("content-type", "application/json");
//            resp.putHeader("connection", "Keep-Alive");
//
//            JsonObject js = new JsonObject().put("ke","demos");
//            resp.end(js.encode());
//        });

        httpServer.requestHandler(this::handleRequest);
        httpServer.listen(8888,"127.0.0.1",res -> {
            if (res.succeeded()) {
                startPromise.complete();
                logger.info("HTTP server started on port 8888");
            } else {
                startPromise.fail(res.cause());
                logger.error(res.cause().getMessage());
            }
        });
    }

    private void handleRequest(HttpServerRequest request){
        request.bodyHandler(body -> {
            HttpServerResponse resp = request.response().setStatusCode(200);
            resp.putHeader("content-type", "application/json");
            resp.putHeader("connection", "Keep-Alive");

            //解析上传的json数据
            JsonObject upData = AbstractMessage.decodeUpMessage(body);
            if(upData == null){
                //上传json参数有误
                AbstractDownMessage output = new NetDownError((short)-1, HttpStatus.JSON_ERROR);
                output.encode();
                resp.end(output.SendMessage());

                logger.error("json error: \n" + body.toString());
                return;
            }

            AbstractDownMessage output;
            short messageId = upData.getInteger("mId",-1).shortValue();
            MessageFactory input = recognizer.recognize(messageId);
            if(input == null){
                output = new NetDownError((short)-1,HttpStatus.ERROR);
                output.encode();
                resp.end(output.SendMessage());
                return;
            }

            InterHandler handlerManager = HandlerManager.getInstance().getHandler(messageId);
            if(handlerManager == null){
                logger.error("not handler :"+messageId);
                output = new NetDownError(messageId,HttpStatus.ERROR);
                output.encode();
                resp.end(output.SendMessage());
                return;
            }

            input.decode(messageId,upData,request);
            handlerManager.handler((AbstractUpMessage)input,resp);
        });
    }

    @Override
    public void stop(){
        httpServer.close();
        logger.error(" AppLogin Server stop ------");
    }

 

四:因为还没有测试handler,所以启动服务器返回会返回code:501

 

项目结构:

 

posted @ 2021-07-14 15:50  Joy_CShow  阅读(283)  评论(0编辑  收藏  举报