繁体   English   中英

Spring Boot Reactive - 如何将数组响应转换为实际的 DTO 对象?

[英]Spring Boot Reactive - How to convert Array response to actual DTO object?

我正在使用 Spring WebFlux 开发 Spring Boot 2.7.0 和反应式微服务。

下面是代码

public void placeOrder(OrderRequest orderRequest) {
        List<OrderLineItems> orderLineItems = orderRequest.getOrderLineItemsDtoList()
                .stream()
                .map(this::mapToDto)
                .collect(Collectors.toList());

        Order order = new Order();
        order.setOrderNumber(UUID.randomUUID().toString());
        order.setOrderLineItemsList(orderLineItems);


        List<String> skuCodes = order.getOrderLineItemsList()
                .stream()
                .map(orderLineItem -> orderLineItem.getSkuCode())
                .collect(Collectors.toList());

        // Call Inventory Service, and place order if product is in stock
        InventoryResponse[] inventoryResponsArray = webClient.get()
                .uri("http://localhost:8092/api/inventory",
                        uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .block();

        boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
                .allMatch(InventoryResponse::isInStock);

        if(allProductsInStock){
            orderRepository.save(order);
        } else {
            throw new IllegalArgumentException("Product is not in stock, please try again later");
        }
    }

有没有办法将以下两个代码合二为一?

// Call Inventory Service, and place order if product is in stock
        InventoryResponse[] inventoryResponsArray = webClient.get()
                .uri("http://localhost:8092/api/inventory",
                        uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .block();

        boolean allProductsInStock = Arrays.stream(inventoryResponsArray)
                .allMatch(InventoryResponse::isInStock);

我能想到的最简单的解决方案如下:

// Call Inventory Service, and place order if product is in stock
boolean allProductsInStock = webClient.get()
                .uri("http://localhost:8092/api/inventory", uriBuilder -> uriBuilder.queryParam("skuCode", skuCodes).build())
                .retrieve()
                .bodyToMono(InventoryResponse[].class)
                .map(e -> Arrays.stream(e))
                .block()
                .allMatch(InventoryResponse::isInStock);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM