向其他微服务发起 HTTP 请求
本指南将向你展示如何使用 Vert.x 向其他微服务或外部服务发起异步非阻塞 HTTP 请求。
你将构建什么
你将构建一个 Vert.x 应用程序,调用 https://icanhazdadjoke.com/api 提供的公开 API,并每隔 3 秒在控制台输出一条新笑话:
整个应用程序仅包含一个简洁的 JokeVerticle 类。
前置要求
-
文本编辑器或 IDE
-
Java 11 或更高版本
-
Maven 或 Gradle
创建工程项目
本项目代码同时提供了功能等价的 Maven 与 Gradle 构建配置。
使用 Maven
以下是你应当使用的 pom.xml 构建配置文件内容:
pom.xml<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.vertx.howtos</groupId>
<artifactId>http-client-howto</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<vertx.version>5.0.0.CR2</vertx.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-stack-depchain</artifactId>
<version>${vertx.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-core</artifactId>
</dependency>
<dependency>
<groupId>io.vertx</groupId>
<artifactId>vertx-web-client</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>11</release>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<mainClass>io.vertx.howtos.httpclient.JokeVerticle</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
使用 Gradle
如果你偏好使用搭配 Kotlin DSL 的 Gradle,对应的 build.gradle.kts 文件如下所示:
build.gradle.ktsplugins {
java
application
}
repositories {
mavenCentral()
}
dependencies {
val vertxVersion = "5.0.0.CR2"
implementation("io.vertx:vertx-core:${vertxVersion}")
implementation("io.vertx:vertx-web-client:${vertxVersion}")
}
application {
mainClass = "io.vertx.howtos.httpclient.JokeVerticle"
}
使用 Vert.x Web 客户端获取数据
相比 Vert.x Core 中相对底层的 HTTP 客户端 API,Vert.x Web Client(Web 客户端)极大地简化了 HTTP 请求的发起与响应解析。
WebClient 类位于 io.vertx:vertx-web-client 依赖库中。
为了不断获取新笑话,我们需要向 https://icanhazdadjoke.com/api 发送 HTTP GET 请求。 为了每隔 3 秒触发一次请求,我们可以直接使用 Vert.x 的周期性定时器(Periodic Timer)。
该 API 返回标准的 JSON 对象格式。
我们可以使用命令行工具(如 curl)进行前置测试:
$ curl -H "Accept: application/json" https://icanhazdadjoke.com/
{"id":"IJBAsrrzPmb","joke":"What do you call a cow with two legs? Lean beef.","status":200}
以下是 JokeVerticle 类的完整实现代码:
package io.vertx.howtos.httpclient;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpResponseExpectation;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.codec.BodyCodec;
public class JokeVerticle extends AbstractVerticle {
private HttpRequest<JsonObject> request;
@Override
public void start() {
request = WebClient.create(vertx) (1)
.get(443, "icanhazdadjoke.com", "/") (2)
.ssl(true) (3)
.putHeader("Accept", "application/json") (4)
.as(BodyCodec.jsonObject()); (5)
vertx.setPeriodic(3000, id -> fetchJoke());
}
private void fetchJoke() {
request.send()
.expecting(HttpResponseExpectation.SC_OK) (6)
.onSuccess(result -> {
System.out.println(result.body().getString("joke")); (7)
System.out.println("🤣");
System.out.println();
})
.onFailure(e -> System.out.println("No joke fetched: " + e.getMessage()));
}
public static void main(String[] args) {
Vertx vertx = Vertx.vertx();
vertx.deployVerticle(new JokeVerticle()).await();
}
}
| 1 | 获取绑定到当前 Vert.x 实例的 WebClient 客户端。 |
| 2 | 向主机 icanhazdadjoke.com 的 443 端口(HTTPS)路径 / 发起 HTTP GET 请求。 |
| 3 | 务必记得开启 SSL/TLS 加密传输。 |
| 4 | 显式设置请求头,声明期望接收 JSON 格式响应。 |
| 5 | Vert.x 会自动将响应数据解析并转换为 JSON 对象。 |
| 6 | 声明期望服务端返回 HTTP 200 状态码,否则该请求 Future 将自动标记为失败。 |
| 7 | 响应体为 JSON 对象,我们提取其中的笑话正文字段并打印至控制台。 |
运行应用程序
JokeVerticle 类中已内置了 main 方法,因此可以直接运行以实现:
-
创建
Vertx核心上下文; -
部署并启动
JokeVerticle。
你可以通过以下方式启动该应用:
-
在你的 IDE 中直接运行
JokeVerticle类的main方法; -
使用 Maven:
mvn compile exec:java; -
使用 Gradle:
./gradlew run(Linux/macOS)或gradle run(Windows)。
本文总结
通过本指南,我们系统学习了:
-
使用 Vert.x Web Client 高效发起 HTTP 异步请求;
-
自动反序列化并提取 JSON 响应内容;
-
使用 Vert.x 周期性定时任务调度执行业务操作。