简体   繁体   English

Reactor Flux:如何使用 header 解析文件

[英]Reactor Flux: how to parse file with header

Recently I started using project reactor 3.3 and I don't know what is the best way to handle flux of lines, with first line as column names, then use those column names to process/convert all other lines.最近我开始使用 project reactor 3.3,我不知道处理行流量的最佳方法是什么,第一行作为列名,然后使用这些列名来处理/转换所有其他行。 Right now I'm doing this way:现在我正在这样做:

Flux<String> lines = ....;
Mono<String[]> columns = Mono.from(lines.take(1).map(header -> header.split(";"))); //getting first line
Flux<SomeDto> objectFlux = lines.skip(1) //skip first line
  .flatMapIterable(row -> //iterating over lines
      columns.map(cols -> convert(cols, row)));  //convert line into SomeDto object

So is it the right way?那么这是正确的方法吗?

So is it the right way?那么这是正确的方法吗?

There's always more than one way to cook an egg - but the code you have there seems odd / suboptimal for two main reasons:煮鸡蛋的方法总是不止一种——但你那里的代码看起来很奇怪/不是最理想的,主要有两个原因:

  • I'd assume it's one line per record / DTO you want to extract, so it's a bit odd you're using flatMapIterable() rather than flatMap()我假设您要提取的每条记录/ DTO 一行,所以您使用flatMapIterable()而不是flatMap()有点奇怪
  • You're going to resubscribe to lines once for each line, when you re-evaluate that Mono .当您重新评估Mono时,您将为每lines重新订阅一次。 That's almost certainly not what you want to do.这几乎肯定不是你想要做的。 (Caching the Mono helps, but you'd still resubscribe at least twice.) (缓存Mono会有所帮助,但您仍需至少重新订阅两次。)

Instead you may want to look at using switchOnFirst() , which will enable you to dynamically transform the Flux based on the first element (the header in your case.) This means you can do something like so:相反,您可能想查看使用switchOnFirst() ,这将使您能够根据第一个元素(在您的情况下为 header)动态转换Flux 。这意味着您可以执行以下操作:

lines
        .switchOnFirst((signal, flux) -> flux.zipWith(Flux.<String[]>just(signal.get().split(";")).repeat()))
        .map(row -> convert(row.getT1(), row.getT2()))

Note this is a bear-bones example, in real-world use you'll need to check whether the signal actually has a value as per the docs:请注意,这是一个熊骨头示例,在实际使用中,您需要根据文档检查signal是否实际具有值:

Note that the source might complete or error immediately instead of emitting, in which case the Signal would be onComplete or onError.请注意,源可能会立即完成或出错,而不是发出,在这种情况下,信号将是 onComplete 或 onError。 It is NOT necessarily an onNext Signal, and must be checked accordingly.它不一定是 onNext 信号,必须进行相应检查。

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

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