To call an external service (API) correctly in a reactive Quarkus application using Vertx and Mutiny, use the following steps:
Mutiny.Vertx
instance:Mutiny.Vertx vertx = Mutiny.Vertx.vertx();
WebClient
instance using the Vertx
instance:WebClient webClient = WebClient.create(vertx);
WebClient
instance:Uni<HttpResponse<Buffer>> response = webClient.get(8080, "external-service.com", "/api/resource")
.addQueryParam("param", "value")
.send();
Uni
instance using the onItem
method:response.onItem().transform(resp -> parseResponse(resp.bodyAsString())).subscribe().with(result -> {
// Process the response
});
Parse the response using the appropriate method, such as JsonObject.mapFrom
or Json.decodeValue
.
Use appropriate error handling techniques such as using .onFailure().retry().atMost(3)
to retry the HTTP request a few times if it fails.
Example code:
public Uni<MyResponse> callExternalService() {
Mutiny.Vertx vertx = Mutiny.Vertx.vertx();
WebClient webClient = WebClient.create(vertx);
Uni<HttpResponse<Buffer>> response = webClient.get(8080, "external-service.com", "/api/resource")
.addQueryParam("param", "value")
.send();
return response.onItem().transform(resp -> parseResponse(resp.bodyAsString()))
.onFailure().retry().atMost(3);
}
private MyResponse parseResponse(String responseJson) {
JsonObject responseObj = JsonObject.mapFrom(responseJson);
// ...
return myResponse;
}
Asked: 2023-01-29 11:00:00 +0000
Seen: 11 times
Last updated: Feb 21 '23