java - 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. :)
解决方案
当您需要顺序、异步和延迟执行时,请使用流水线。在所有其他情况下(当您使用非阻塞代码时)您可以自由选择任何方法,通常最好使用最简单的方法。
顺序非阻塞代码可以组织成函数,您可以使用 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)
}
}
推荐阅读
- node.js - Nodejs https 函数需要等待 url json 响应并将其传递回调用 express 模块作为响应以在客户端打印
- python - numpy 数组索引技术如何为相同的输入代码提供不同的输出?
- java - 在运行 gradle eclipse 任务之前是否需要关闭 Eclipse?
- java - 动态地将 ArrayList 添加到另一个 ArrayList 是踩值
- python - 在带有 selenium 的 python 中,如何轮换 IP 地址?
- jquery - 根据子类或兄弟类获取父元素或上一个元素
- torchscript - 无法让 torch.jit.script 与 pytorch RNN 一起正常工作
- python - Github 创建数据库文件 discord.py
- python - (Tensorflow)TypeError:create_estimator_and_inputs()缺少1个必需的位置参数:'hparams'
- c# - Xamarin.Forms - 多次加载其中的图像时扩展框架