使用 vertx & mutiny 在 quarkus 响应式应用程序中调用外部服务 (API) 的正确方法是什么?



我是一个新的响应式编程与vertx &muntiny (quarkus)。我有以下要求:

结构:外部API调用返回->响应

class Response {String abc; List<AnotherClass> another; ...}
class AnotherClass { List<Role>> roles ...}

DB调用返回Uni<List<RoleFromDB>> rolesDB

我希望下面的调用在一个链中以响应的方式完成。有没有人能指导我如何正确地做这件事?

  1. 调用外部API。2. 使用响应式Hibernate调用DB (postgres)从API接收到的一些id值。3.将DB查询结果添加到API的结果中,并作为新的Uni<Response>
  2. 返回

你还能给我展示一个以响应式方式调用外部API的例子吗?我在网上找不到合适的资料。

这就是我正在做的。

Uni<List<RolesfromDB>> roles == db call returning Uni<List<RoleFromDB>>

roles.chain(role -> {
Response res = Unirest.get(url).header(...);
//Is calling external endpoint this way fine?
Uni<Response> uniRes = Uni.createFrom().item(res);
//do some operation with uniRes to assign role to the response object and return a new Uni<Response> ...
});

这是正确的吗?或者我需要使用其他方式,如

io.vertx.axle.ext.web.client.WebClient?

一个正确调用外部API的例子将非常感激。

我推荐两种方法。

  1. 使用响应式REST客户端

当使用响应式REST客户端(参见https://quarkus.io/guides/rest-client-reactive)时,您将创建一个抽象HTTP交互的Java接口。将为您生成代理,因此您不需要低级HTTP客户机。这个响应式客户端同时支持阻塞和非阻塞。因此,在您的示例中,您将拥有如下内容:

@GET
Uni<Response> invokeMyService(Role role)

然后,在你的管道中,你做:

roles.chain(role -> client.invokeMyService(role));
  1. 使用Vert。x Web客户端

这是更低级的,只有在响应式rest客户端不能处理您的特定情况时才应该使用它。在本例中,您将执行如下操作:

public MyClass(Vertx vertx) {  // io.vertx.mutiny.core.Vertx
this.client = WebClient.create(vertx); // io.vertx.mutiny.ext.web.client.WebClient
}
// ...
roles.chain(role -> {
var req = this.client.getAbs(url); // using GET, use the method you need
// Add headers and so on
return req.send()
.map(resp -> resp.bodyAsJsonObject().mapTo(Response.class);
});

最新更新