返回文章列表

文章

Vert.x 教程(二)

使用Vertx构建Restful API

目录
  1. 📝 Web服务的路由配置
  2. 示例代码
  3. 📝构建Restful API
  4. 创建GET请求
  5. 创建POST请求
  6. 📎 参考文章

📝 Web服务的路由配置#

在教程(一)中使用了Router router = Router.router(vertx)这个类就是用来构建不同路由的,代码如下:

示例代码#

package com.example.starter;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.MultiMap;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;

public class MainVerticle extends AbstractVerticle {

    @Override
    public void start(Promise<Void> startPromise) {
        // Create a Router
        Router router = Router.router(vertx);

        // Mount the handler for all incoming requests at every path and HTTP method
        router.route("").handler(context -> {
            // Get the address of the request
            String address = context.request().connection().remoteAddress().toString();
            // Get the query parameter "name"
            MultiMap queryParams = context.queryParams();
            String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
            // Write a json response
            context.json(
                new JsonObject()
                    .put("name", name)
                    .put("address", address)
                    .put("message", "Hello " + name + " connected from " + address)
            );
        });
        // Create the HTTP server
        //省略部分
    }
}

源码地址 router.route()有多个重载的方法可以,没有参数默认就是API就是localhost:8888。 router.route(”/hello”)表示localhost:8888/hello的API,这里没有指定请求方法,默认就是支持所有请求方法,例如GET/POST/PUT/DELETE等请求方式都是支持的。

    public void start(Promise<Void> startPromise) {
        // Create a Router
        Router router = Router.router(vertx);

        // Define a handler for the root path
        router.route("/").handler(this::handleRoot);

        // Define a handler for the /hello path
        router.route("/hello").handler(this::handleHello);

        // Define a handler for the /goodbye path
        router.route("/goodbye").handler(this::handleGoodbye);

        // Create the HTTP server
        vertx.createHttpServer()
            // Handle every request using the routerrequestHandler(router)
            // Start listening
            .listen(8888)
            // Print the port on success
            .onSuccess(server -> {
                System.out.println("HTTP server started on port " + server.actualPort());
                startPromise.complete();
            })
            // Print the problem on failure
            .onFailure(throwable -> {
                throwable.printStackTrace();
                startPromise.fail(throwable);
            });
    }

📝构建Restful API#

前面说默认的路由是支持所有的请求方法,那么我们要创建Restful API要指定请求方式该怎么实现呢。如下所示:

创建GET请求#

        //部分省略
        router.get("/name").handler(this::testGet);
        //部分省略
       
       private void testGet(RoutingContext context) {
        MultiMap queryParams = context.queryParams();
        String name = queryParams.contains("name") ? queryParams.get("name") : "unknown";
        if(name.equals("likanug")) {
            context.json(
                new JsonObject()
                    .put("name", name)
                    .put("message", "Hello " + name)
            );
        }else {
            context.json(
                new JsonObject()
                    .put("message", name + " not found")
            );
        }
    } 

测试结果如下: 请求方式改成POST时候,请求被拒绝

创建POST请求#

举一反三,我们可以推测,创建POST请求,应该是router.post("/user").handler(this::testPost)这种形式,根据查看router的API和相关文档确实如此,PUT和DELETE请求以此类推,在此不一样赘述。 具体示例见github代码仓库

📎 参考文章#