You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Quarkus响应式编程中如何定义两个客户端调用的依赖关系

问题根因

你当前出现Uni<Uni<FullCustomer>>类型嵌套的核心原因是错误使用了onItem().transform()方法:

  • transform()用于同步转换上游发射的元素,直接返回普通Java对象即可
  • 当你的转换逻辑需要返回另一个Uni做异步调用时,必须使用onItem().transformToUni(),它会自动将返回的Uni展开,不会产生嵌套包装。

修正后代码

@GET
@Path("api/customer/{id}")
@Produces({ "application/json" })
Uni<FullCustomer> getFullCustomer(@PathParam("id") String customerID){
    Uni<Customer> customerResponse = getCustomer(customerID);
    // 第一层用transformToUni处理异步转换,自动展开Uni
    return customerResponse.onItem().transformToUni(customer -> {
        if (customer.getAddressId() != null) {
            Uni<Address> addressResponse = getAddress(customer.getAddressId());
            return addressResponse.onItem().transform(address -> {
                if (address.getShippingAddress() != null) {
                    return new FullCustomer(customer, address.getShippingAddress());
                } else {
                    return new FullCustomer(customer);
                }
            });
        }
        // 直接返回包装好的Uni即可,transformToUni会自动拼接流
        return Uni.createFrom().item(new FullCustomer(customer));
    });
}

补充说明

修改后的代码完全保留了异步非阻塞特性,没有任何阻塞调用:

  1. 先异步获取客户信息
  2. 如果客户存在地址ID,继续异步获取地址信息
  3. 所有转换逻辑都在响应式流中完成,最终直接返回Uni<FullCustomer>类型符合接口要求

内容的提问来源于stack exchange,提问作者Rajat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 08:45:06