【问题标题】:Calculating deltas in Apache Beam using Stateful processing使用有状态处理计算 Apache Beam 中的增量
【发布时间】:2018-08-10 15:31:06
【问题描述】:

我有一堆输入流,它们可能会随着时间的推移发送更新。如果发生更新,我需要计算增量以便能够进一步处理它。简而言之:

Input: 10 -> State: 10, Output: 10
Input: 12 -> State: 12, Output:  2
Input:  5 -> State:  5, Output: -7

我阅读了 stateful processing 和 timely processing 以了解如何在 Apache Beam 应用程序中处理这种状态,但我不知道的是:

  1. 是否 100% 保证我的有状态 DoFn 不会并行处理具有相同键的项目?
  2. 我想确保在我的应用程序重新启动或失败时保持状态,以便我可以从正确的初始值开始。如何确保我的 DoFn 在关闭之前“清理”(保留到数据存储区)?

对于#2,我想知道这在使用全局窗口时是否可行:

public class Delta extends DoFn<KV<String, Integer>, Integer> {
    @StateId("state")
    private final StateSpec<ValueState<Integer>> stateSpec = StateSpecs.value();

    @TimerId("timer")
    private final TimerSpec timerSpec = TimerSpecs.timer(TimeDomain.EVENT_TIME);

    @ProcessElement
    public void process(ProcessContext context,
                        BoundedWindow window,
                        @StateId("state") ValueState<Integer> state,
                        @TimerId("timer") Timer myTimer) {
        // Assign the timer to the end of the current window, which is a global window
        // Not sure if this always triggers when the application stops...
        myTimer.set(window.maxTimestamp());

        int value = context.element().getValue();
        int acc = getOrInitialize(state.read());
        int delta = value - acc;
        state.write(value);
        context.output(delta);
    }

    @OnTimer("timer")
    public void onTimer(OnTimerContext context,
                        @StateId("state") ValueState<Integer> state) {
        // Persist value of state here
    }

    private int getOrInitialize(Integer a) {
        // Get initial value of state here
        return (a != null) ? a : 0;
    }
}

【问题讨论】:

    标签: java apache-beam


    【解决方案1】:
    1. 是的
    2. 我认为如果不配置任何BoundedWindow,您的计时器方法将无法工作。 @StartBundle/@Setup 和 @FinishBundle 应该是更好的恢复和检查点的地方。我不推荐@Teardown,因为它不能保证被调用。

    【讨论】:

    • 我一直在查看 @StartBundle 和 @FinishBundle 的文档,但它们似乎不支持 StateId 注释来提供对状态的访问。
    • 对不起,我没有意识到这一点。一种解决方法是使用外部数据库(例如 Cloud Datastore、Cloud BigTable 等),但此时您可能根本不需要使用 Apache Beam。另一种解决方法是使用处理计时器来检查点值。但是,当管道重新启动时,并不能保证所有内容都会被检查点
    • 我实际上打算使用 Cloud Datastore 来保存每个键的“当前”值。我试图解决的问题与我们的一个来源同时发布大量更新时发生的竞争条件有关。为什么我在处理数据库时不需要使用 Beam?
    • Datastore 支持事务:您可以读取、计算增量并在事务中存储新值。如果提交失败,则需要一些重试逻辑。一个简单的 Web 服务就可以做到这一点。您不一定需要使用 Apache Beam。如果您仍然想使用它,它不会受到伤害。
    • 嗯,增量计算只是更大管道的一小部分,不幸的是,这不是 Web 服务可以轻松处理的。
    【解决方案2】:
    1. 有状态处理是按键和窗口并行化的。可以并行处理相同键但不同窗口的两个元素。但是您的元素都在全局窗口中,因此在您的情况下它与每个键的并行性相同。

    2. 使用计时器刷新状态是正确的想法。全局窗口末尾的事件时间计时器在正常管道操作期间永远不会触发,但会在所有水印移动到无穷大的“耗尽”场景中触发。 Drain 是 Cloud Dataflow 的一项功能,已被提议作为跨 Beam 的可移植概念,但您应该查看您选择的 runner 是否具有此类功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-13
      • 2021-11-11
      • 2019-01-25
      • 2021-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多