WebFlux:从通量对象获取属性并将通量链接到下一个

问题描述 投票:0回答:1

我有一系列网络客户端调用,如下所示。

  1. 从第一次 API 调用中获取
    Flux<RecordA>
  2. 从 Record 中获取一些属性,比如 prop,从每个记录 (
    List<Long>
    )
  3. 调用另一个 API 来获取唯一属性值列表并获取详细信息
  4. 根据 prop 字段,使用从步骤 3 收到的数据更新第一步中的
    Flux<RecordA>
    对象值。
  5. 返回最终更新记录

那么如何将通量从步骤 1 传递到步骤 4?

java spring-boot spring-webflux
1个回答
0
投票

通量是数据记录流。在每条记录上,您描述一个处理步骤列表,以计算上一步的新状态/记录。

如果可能,我建议您使用新状态复制记录,而不是尝试更新现有实例。

举个例子:

  • 给定以下数据模型:
record RecordA(Long id, List<Long> tagIds, List<String> tagDescriptions)
  • 给定一个 API 来获取给定“标签”的描述:
public static Mono<String> fetchTagDescription(Long tagId) {
     if (tagId == null) return Mono.error(new IllegalArgumentException("Null ids not accepted"));
     // Mimic external API call
     return Mono.just("Description for tag "+tagId);
}
  • 当您收到
    Flux<RecordA
    时,您可以获取每条记录的标签描述,然后创建包含标签描述的最新副本,如下所示:
public static Flux<RecordA> updateTagDescription(Flux<RecordA> records) {
    return records.flatMap(record -> {
        if (record.tagIds() == null || record.tagIds().isEmpty()) {
            return Mono.just(record);
        }
        return Flux
            .fromIterable(record.tagIds())
            .concatMap(tagId -> fetchTagDescription(tagId))
            .collectList()
            .map(descriptions -> new RecordA(record.id(), record.tagIds(), descriptions));
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.