【问题标题】:How to process historical data using Reactor?如何使用 Reactor 处理历史数据?
【发布时间】:2022-01-03 10:45:23
【问题描述】:

假设我有两个历史事件来源,并且每个来源的事件都按时间顺序排列。

如何使用 Reactor 合并这些源,以便合并 Flux 中的事件按时间顺序发出?

在 RxNET 中,Observable.Generate()HistoricalScheduler 的组合可用于从历史事件源创建 Observable,以便根据事件的时间安排排放(详细信息 here) ,但我无法在 Reactor 中找到等效的方法。

也许我可以以某种方式将Flux.generate()VirtualTimeScheduler 一起使用?

下面是一个玩具示例:

public class Program {

  public record Event(Instant time, String id) {}

  public static void main(String[] args) {

    var source1 = Arrays.asList(
        new Event(Instant.ofEpochMilli(10), "a"),
        new Event(Instant.ofEpochMilli(30), "c"),
        new Event(Instant.ofEpochMilli(50), "e")
    );

    var source2 = Arrays.asList(
        new Event(Instant.ofEpochMilli(20), "b"),
        new Event(Instant.ofEpochMilli(40), "d"),
        new Event(Instant.ofEpochMilli(60), "f")
    );

    Flux.fromIterable(source1)
        .mergeWith(Flux.fromIterable(source2))
        .subscribe(e -> System.out.println(e.id));

    // current output:
    // a
    // c
    // e
    // b
    // d
    // f

    // desired output:
    // a
    // b
    // c
    // d
    // e
    // f
   
  }
}

【问题讨论】:

    标签: java event-handling reactive-programming project-reactor reactive-streams


    【解决方案1】:

    您可以使用mergeComparingWith 运算符并像这样提供Comparator

    Flux.fromIterable(source1)
             .mergeComparingWith(Flux.fromIterable(source2), Comparator.comparing(Event::time, Instant::compareTo))
             .subscribe(e -> System.out.println(e.id));
    

    它通过从每个序列中选取最小值来生成重新排序的合并序列。

    【讨论】:

    • 谢谢,这很有帮助。现在是否可以将基于时间的运算符(例如,window)应用于合并的序列,以便运算符尊重事件时间而不是实际时间?
    • @jack 不是真的。那时,对象具有时间戳或其他东西的事实并没有反映在发射的时间上:fromIterable 只会尽可能快地重放它们。巧妙地使用诸如 concatMap 和 Mono.delay 之类的运算符可能是可能的,但您必须设法将时间戳转换为适当的延迟......
    • 也就是说,Rx 中的 HistoricalScheduler 似乎与 Reactor 中的 VirtualTimeScheduler 非常相似。我想知道是否可以实施一些技术来使用它。 window(Duration, Scheduler) 可以使用,但棘手的部分是如何推进调度程序
    • 明白。感谢您的回复。非常感谢您在反应堆上所做的工作!
    猜你喜欢
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 2018-12-17
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多