简体   繁体   English

Spring在无效方法中反应

[英]Spring Reactive in void methods

I am facing difficulties in understand reactive stream principles, and getting problem with a simple solution that is easy solved by java 8 streams. 我在理解反应式流原理时遇到了困难,并且在使用Java 8流可以轻松解决的简单解决方案时遇到了问题。 I would like to do this: 我想这样做:

class service{
public void add(List<Car> cars){
 cars.parallelStream.forEach(car -> repo.add(car));
}

using Spring Reactor implementation. 使用Spring Reactor实现。 I saw many examples on internet but usually with object mapping or something like this. 我在互联网上看到了许多示例,但通常都涉及对象映射或类似的东西。

Spring reactor has 2 types of publishers: Spring Reactor有2种类型的发布者:

  1. Mono-contains 0(empty) or 1 element in the stream. 流中单声道包含0(空)或1个元素。
  2. Flux-contains 0-N elements in the stream. 助焊剂在流中包含0-N个元素。

Since you get a list of Car objects, we have to use Flux publisher. 由于您获得了Car对象的列表,因此我们必须使用Flux Publisher。

To create a publisher having the elements contained in the list, you have to do the following: 要创建具有包含在列表中的元素的发布者,您必须执行以下操作:

Flux.fromIterable(cars);

This gives you a publisher which emits objects of the Car. 这给您一个发布汽车对象的发布者。

Another point is that, since its spring reactor now, you have to change the return type of service as well as repository method to Mono<Void> and the repository must extend the reactive repository (as per the database you are using) 另一点是,由于它现在是弹簧反应堆,因此您必须将服务的返回类型以及存储库方法更改为Mono<Void>并且该存储库必须扩展反应性存储库(根据您使用的数据库)

Now to add the objects in repository, you would have to do the following: 现在要在存储库中添加对象,您将必须执行以下操作:

Flux.fromIterable(cars)
.flatMap(car->repo.add(car));

Using the flatMap operator you make the async repo calls. 使用flatMap运算符,您可以进行异步回购调用。 To know what goes inside flatMap, go here . 要了解flatMap内部内容,请转到此处 Hope this gives you some idea ok how to use spring reactor. 希望这可以给您一些想法,如何使用弹簧反应堆。

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

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