1 回答

TA貢獻1876條經驗 獲得超6個贊
當您需要順序、異步和延遲執行時,請使用流水線。在所有其他情況下(當您使用非阻塞代碼時),您可以自由選擇任何方法,通常最好使用最簡單的方法。
順序非阻塞代碼可以組織成函數,您可以使用 map/filter/doOnNext/... 組件將這些函數與反應式管道集成。
例如,考慮以下Order價格計算代碼。
class PriceCalculator {
private final Map<ProductCode, Price> prices;
PriceCalculator(Map<ProductCode, Price> prices) {
this.prices = prices;
}
PricedOrder calculatePrice(Order order) { // doesn't deal with Mono/Flux stuff
Double price = order.orderLines.stream()
.map(orderLine -> prices.get(orderLine.productCode))
.map(Price::doubleValue)
.sum();
return new PricedOrder(order, price);
}
}
class PricingController {
public Mono<PricedOrder> getPricedOrder(ServerRequest request) {
OrderId orderId = new OrderId(request.pathVariable("orderId"));
Mono<Order> order = orderRepository.get(orderId);
return order.map(priceCalculator::calculatePrice)
}
}
添加回答
舉報