Ask Your Question
4

How can an external service (API) be called correctly in a reactive quarkus application using vertx and mutiny?

asked 2023-01-29 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-02-21 06:00:00 +0000

nofretete gravatar image

To call an external service (API) correctly in a reactive Quarkus application using Vertx and Mutiny, use the following steps:

  1. Obtain the Mutiny.Vertx instance:
Mutiny.Vertx vertx = Mutiny.Vertx.vertx();
  1. Create a WebClient instance using the Vertx instance:
WebClient webClient = WebClient.create(vertx);
  1. Define the HTTP request to the external service using the WebClient instance:
Uni<HttpResponse<Buffer>> response = webClient.get(8080, "external-service.com", "/api/resource")
    .addQueryParam("param", "value")
    .send();
  1. Extract the response from the Uni instance using the onItem method:
response.onItem().transform(resp -> parseResponse(resp.bodyAsString())).subscribe().with(result -> {
    // Process the response
});
  1. Parse the response using the appropriate method, such as JsonObject.mapFrom or Json.decodeValue.

  2. 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;
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-29 11:00:00 +0000

Seen: 11 times

Last updated: Feb 21 '23