首页 > 解决方案 > Where to use Mono/Flux?

问题描述

I'm kind of forced to switch to reactive programming (and in a short time frame), using WebFlux and I'm having a really hard time understanding it. Maybe because the lack of examples or because I never did functional programming.

Anyways, my question is where to use Mono/Flux and where can I work with normal objects? E.g. my controller is waiting for a @Valid User object, should that be @Valid Mono or something like Mono<@Valid User>? If let's say it was just a User object, I pass it to my service layer, and I want to encode the password before saving it to the reactive MongoDb, should I write:

User.setPassword(...);
return reactiveMongoDbRepository.save(user); //returns Mono<User> which is returned by the Controller to the View

Or it should be something like

return Mono.just(user).map.flatmap(setPasswordSomewhereInThisHardToFollowChain).then.whatever.doOnSuccess(reactiveMongoDbRepository::save);

In other words, am I forced to use this pipeline thing EVERYWHERE to maintain reactiveness or doing some steps the imperative way, like unwrapping the object, working on it, and wrapping it back is OK?

I know my question seems to be silly but I don't have the big picture at all, reading books about it didn't really help yet, please be gentle on me. :)

标签: javareactive-programmingspring-webfluxproject-reactor

解决方案


当您需要顺序、异步和延迟执行时,请使用流水线。在所有其他情况下(当您使用非阻塞代码时)您可以自由选择任何方法,通常最好使用最简单的方法。

顺序非阻塞代码可以组织成函数,您可以使用 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)
  }
}

推荐阅读