提问者:小点点

如何从返回单声道的流中创建通量?[副本]


想象一下,我有一个CourseID对象列表(CourseID,Name)。让我们把这个列表称为'CourseNameList'。

当某人将请求发送到“

然而,在发送结果之前,我还需要追加每个课程的价格。价格将从另一个微服务中检索,并返回Mono对象。

因此,用户将看到带有(ID、名称、价格)的课程列表。价格来源于其他服务。

控制器方法可能如下所示

@GetMapping("/courses")
public Flux<Course> gerProducts() {
 courseNameList.stream.map(courseName -> {
      //Make a webClient call to pricing service by sending coureName.getID as parameter and get the 'price' Mono object
      //return the course object with id, name, price
   })
     //Collect and return Flux with contains list of courses!
}

我尝试了多种方法来返回Flux。但是,我不知道怎么做。我需要用等效的(或者更好的)代码替换这些注释。


共2个答案

匿名用户

从通量开始,而不是从列表开始会更好,但是如果不可能,那么从下面的流创建通量,然后使用flatMap而不是map。

@GetMapping("/courses")
public Flux<Course> gerProducts() {
  return Flux.fromStream(courseNameList.stream()).flatMap(courseName -> {
    // Make webClient call which returns mono
  });
}

匿名用户

你可以看看这个例子,自己想出一个解决方案。

// I assumed you have courses list already as you are using a list.
 List<String> list = List.of("a", "bb", "ccccc", "ddd");
 Flux.fromIterable(list)
       // this is where you find the price and append
       .flatMap(a -> Mono.just(a).map(k -> k + ":" + k.length()))                 
       .subscribe(System.out::println);

//output
a:1
bb:2
ccccc:5
ddd:3

但是,如果你有100门课程,你会想一个接一个地打100个电话给这项服务吗。它不会影响性能吗?相反,你能在一次通话中发送课程列表并从服务中获得价格吗?

// you have courses list
List<String> list = List.of("a", "bb", "ccccc", "ddd");

// get the price of all courses in 1 call
Mono.fromSupplier(() -> List.of(1, 2, 5, 3))
        .flatMapIterable(Function.identity())
        .index()
        // map the courses and price
        // I used index. but you could use courseID to map the price
        .map(t -> list.get(t.getT1().intValue()) + ":" + t.getT2())
        .subscribe(System.out::println);