vertx webclient 使用
所属分类 vertx
浏览量 290
https://vertx.io/docs/4.2.7/vertx-web-client/java/
vertx-web 4.3.2
WebClient client = WebClient.create(vertx);
WebClientOptions options = new WebClientOptions()
.setUserAgent("My-App/1.2.3");
options.setKeepAlive(true);
WebClient client = WebClient.create(vertx, options);
In most cases, a Web Client should be created once on application startup and then reused.
Otherwise you lose a lot of benefits such as connection pooling and may leak resources if instances are not closed properly.
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.client.WebClient;
import java.time.LocalDateTime;
public class WebClientDemo {
static Vertx vertx = Vertx.vertx();
static WebClient client = WebClient.create(vertx);
public static void main(String[] args) throws Exception {
System.out.println("hello vertx web client");
// Send a GET request
System.out.println("Send a GET request");
client
.get(8000, "127.0.0.1", "/hello")
.send()
.onSuccess(response ->
System.out.println("success," + response.statusCode() + "," + response.bodyAsString()))
.onFailure(err ->
System.out.println("error," + err));
Thread.sleep(1000);
// sendJsonObject
System.out.println("sendJsonObject");
client
.post(8000, "127.0.0.1", "/api1")
.sendJsonObject(
new JsonObject()
.put("id", 1)
.put("name", "time")
.put("now", LocalDateTime.now().toString())
)
.onSuccess(response ->
System.out.println("success," + response.statusCode() + "," + response.bodyAsString()))
.onFailure(err ->
System.out.println("error," + err));
}
}
上一篇
下一篇
vertx future compose CompositeFuture
vertx future高级组合操作
vertx future 与 CompletionStage 互操作
vertx core http 客户端 例子
MQTT协议简介
MQTT 术语