在本系列的上一篇文章中, 给大家演示了如何搭建 Vertx 的Web开发环境。这次我们继续深入,构建一个简单的 Rest API。
在本系列中,我们使用和 SpringBoot教程 相同的案例 - 一个简单的 Todo Rest API。
构建实体对象
首先,构建一个表达待办事项的实体对象 - Todo, 为了避免实体对象中的维护 Get/Set 代码,我们使用 Lombok 库。 需要在项目的 pom.xml 文件中引入 Lombok 库。 打开项目根目录中的 pom.xml 文件。在依赖中()加入下面的行:
1 2 3 4 5 6
| <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency>
|
然后新建一个名为: cn.com.hohistar.study.vertx.model 的包,在包中新建一个名为: Todo 的类,代码如下:
1 2 3 4 5 6 7 8 9 10 11
| @Data @AllArgsConstructor public class Todo {
private Integer id;
private String title;
private String desc;
}
|
为了使案例简单,我们只在实体中加入了三个属性: id, title 和 desc。
构建一个API
构建好实体后,我们来构建一个简单的 API, 让它返回一个 Todo 对象的信息。
打开在 上一篇文章 中构建的 ApiVerticle 类,在其中增加如下的代码:
1 2 3 4 5 6
| router.route("/api/todo").handler(ctx -> {
Todo todo = new Todo(1, "call tom", "description"); ctx.response().end(todo.toString());
});
|
可以看到,我们加入了一个新的 route, 其处理方法很简单,就是生成一个 Todo 对象,并输出。
运行程序,用浏览器访问
1
| http://localhost:8080/api/todo
|
会得到如下的结果:
1
| Todo(id=1, title=call tom, desc=description)
|
这显然和我们通常使用的 Rest API 不一样,通常 Rest API 是通过 HTTP 协议,使用 JSON 格式来完成调用,传输数据的。
使用 JsonObject 对象
在 Vertx 中, JSON 是最主要的数据格式,所以在 Vertx 中定义了自己的 JsonObject 对象和 JsonArray 对象。下面我们就使用 JsonObject 对象来完成 API, 代码如下:
1 2 3 4 5 6 7 8
| router.route("/api/todo").handler(ctx -> {
JsonObject todo = new JsonObject(); todo.put("id", 1); todo.put("title", "call tom"); todo.put("desc", "description"); ctx.response().end(todo.toString()); });
|
可以看到, JsonObject 对象的使用方式和 Map 类型的使用方式差不多。把数据准备好以后,只需要调用 toString() 方法,就可以得到我们想要的 JSON 格式输出了。
将模型转换为 JsonObject
JsonObject 使用起来虽然方便,但在 Java 中,大家更习惯在业务层中使用实体对象来编写业务逻辑,这样也能充分利用编译器的功能,快速检查出潜在的错误。基于此, JsonObject 也提供了简单的方法让我们把实体转换为 JsonObject。
代码修改如下:
1 2 3 4 5 6
| router.route("/api/todo").handler(ctx -> {
Todo todo = new Todo(1, "call tom", "description");
ctx.response().end(JsonObject.mapFrom(todo).toString()); });
|
通过 JsonObject 的 mapFrom 方法,我们可以把实体直接转为 JsonObject 对象。
完整代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| public class ApiVerticle extends AbstractVerticle {
private HttpServer server = null;
@Override public void start(Future<Void> startFuture) throws Exception {
server = vertx.createHttpServer();
Router router = Router.router(vertx);
router.route("/ok").handler(ctx -> { ctx.response().end("ok"); });
router.route("/api/todo").handler(ctx -> {
Todo todo = new Todo(1, "call tom", "description");
ctx.response().end(JsonObject.mapFrom(todo).toString()); });
HttpServerOptions options = new HttpServerOptions();
server.requestHandler(router).listen(8080, result -> {
if (result.succeeded()) {
System.out.println("Todo Service startup in port: " + result.result().actualPort());
startFuture.succeeded();
} else {
result.cause().printStackTrace();
startFuture.failed();
}
}); } }
|
下一步
在下一篇文章中,将介绍如何如何统一输出格式。