Flink-v1.12官方网站翻译-P023-The Broadcast State Pattern

广播状态模式

 

 

 

在本节中,您将了解如何在实践中使用广播状态。请参考状态流处理,了解状态流处理背后的概念。

 

提供的API

 

为了展示所提供的API,我们将在介绍它们的全部功能之前先举一个例子。作为我们的运行示例,我们将使用这样的情况:我们有一个不同颜色和形状的对象流,我们希望找到相同颜色的对象对,并遵循特定的模式,例如,一个矩形和一个三角形。我们假设有趣的模式集会随着时间的推移而演变。

 

在这个例子中,第一个流将包含具有颜色和形状属性的 Item 类型的元素。另一个流将包含规则。

 

从Items流开始,我们只需要按Color键入,因为我们想要相同颜色的对子。这将确保相同颜色的元素最终出现在同一台物理机上。

 

// key the items by color
KeyedStream<Item, Color> colorPartitionedStream = itemStream
                        .keyBy(new KeySelector<Item, Color>(){...});

  

继续讨论规则,包含规则的流应该被广播到所有下游任务,这些任务应该将它们存储在本地,以便它们可以根据所有传入的项目评估它们。下面的代码段将i)广播规则流,ii)使用提供的MapStateDescriptor,它将创建规则将被存储的广播状态。

 

// a map descriptor to store the name of the rule (string) and the rule itself.
MapStateDescriptor<String, Rule> ruleStateDescriptor = new MapStateDescriptor<>(
			"RulesBroadcastState",
			BasicTypeInfo.STRING_TYPE_INFO,
			TypeInformation.of(new TypeHint<Rule>() {}));
		
// broadcast the rules and create the broadcast state
BroadcastStream<Rule> ruleBroadcastStream = ruleStream
                        .broadcast(ruleStateDescriptor);

  

最后,为了根据从Item流传入的元素来评估Rules,我们需要。

  1. 连接两个流,并且
  2. 指定我们的匹配检测逻辑。

将一个流(键控或非键控)与BroadcastStream连接起来,可以通过在非广播流上调用connect()来完成,并将BroadcastStream作为一个参数。这将返回一个BroadcastConnectedStream,我们可以在这个Stream上调用一个特殊类型的CoProcessFunction来处理。该函数将包含我们的匹配逻辑。该函数的具体类型取决于非广播流的类型。

  • 如果它是键控的,那么这个函数就是键控的广播处理函数(KeyedBroadcastProcessFunction).
  • 如果是非键控的,那么该函数就是一个BroadcastProcessFunction。

鉴于我们的非广播流是键控的,下面的代码段包含了上述调用。

注意:连接应该在非广播流上调用,以BroadcastStream作为参数。连接应该在非广播流上调用,以BroadcastStream作为参数

DataStream<String> output = colorPartitionedStream
                 .connect(ruleBroadcastStream)
                 .process(
                     
                     // type arguments in our KeyedBroadcastProcessFunction represent: 
                     //   1. the key of the keyed stream
                     //   2. the type of elements in the non-broadcast side
                     //   3. the type of elements in the broadcast side
                     //   4. the type of the result, here a string
                     
                     new KeyedBroadcastProcessFunction<Color, Item, Rule, String>() {
                         // my matching logic
                     }
                 );

  

BroadcastProcessFunction和KeyedBroadcastProcessFunction

与CoProcessFunction一样,这些函数有两个处理方法要实现;processBroadcastElement()负责处理广播流中的传入元素,processElement()用于处理非广播流。这些方法的完整签名如下。

public abstract class BroadcastProcessFunction<IN1, IN2, OUT> extends BaseBroadcastProcessFunction {

    public abstract void processElement(IN1 value, ReadOnlyContext ctx, Collector<OUT> out) throws Exception;

    public abstract void processBroadcastElement(IN2 value, Context ctx, Collector<OUT> out) throws Exception;
}

  

public abstract class KeyedBroadcastProcessFunction<KS, IN1, IN2, OUT> {

    public abstract void processElement(IN1 value, ReadOnlyContext ctx, Collector<OUT> out) throws Exception;

    public abstract void processBroadcastElement(IN2 value, Context ctx, Collector<OUT> out) throws Exception;

    public void onTimer(long timestamp, OnTimerContext ctx, Collector<OUT> out) throws Exception;
}

  

首先需要注意的是,这两个函数在处理广播端元素时都需要实现processBroadcastElement()方法,在处理非广播端元素时需要实现processElement()方法。

这两个方法在提供的上下文中有所不同。非广播侧有一个ReadOnlyContext,而广播侧有一个Context。

这两个上下文(以下枚举中的ctx)。

  1. 提供对广播状态的访问:ctx.getBroadcastState(MapStateDescriptor<K, V> stateDescriptor)
  2. 允许查询元素的时间戳:ctx.timestamp()。
  3. 获取当前水印:ctx.currentWatermark()
  4. 获取当前处理时间:ctx.currentProcessingTime(),以及
  5. 将元素发射到侧面输出:ctx.output(OutputTag<X> outputTag, X value)。

getBroadcastState()中的stateDescriptor应该和上面的.broadcast(ruleStateDescriptor)中的stateDescriptor是一样的。

区别在于各自对广播状态的访问类型。广播端对其有读写访问权,而非广播端则只有读的访问权(因此才有这些名字)。原因是在Flink中,不存在跨任务通信。所以,为了保证广播状态中的内容在我们操作符的所有并行实例中都是相同的,我们只给广播侧读写访问权,而广播侧在所有任务中看到的元素都是相同的,并且我们要求该侧每个传入元素的计算在所有任务中都是相同的。忽略这个规则会打破状态的一致性保证,导致结果不一致,而且往往难以调试。

注意 `processBroadcastElement()`中实现的逻辑必须在所有并行实例中具有相同的确定性行为!
最后,由于KeyedBroadcastProcessFunction是在键控流上运行的,它暴露了一些BroadcastProcessFunction无法实现的功能。那就是

  1. processElement()方法中的ReadOnlyContext允许访问Flink的底层定时器服务,它允许注册事件和/或处理时间定时器。当一个定时器发射时,onTimer()(如上图所示)被调用一个OnTimerContext,它暴露了与ReadOnlyContext相同的功能,再加上
    • 能够询问发射的定时器是事件还是处理时间一和
    • 来查询与定时器相关联的键。
  2. processBroadcastElement()方法中的Context包含applyToKeyedState(StateDescriptor<S, VS> stateDescriptor, KeyedStateFunction<KS, S> function)方法。这允许注册一个KeyedStateFunction,以应用于与提供的stateDescriptor相关联的所有键的所有状态。

注意。注册定时器只能在`KeyedBroadcastProcessFunction`的`processElement()`处进行,而且只能在那里进行。在`processBroadcastElement()`方法中是不可能的,因为没有键与广播元素相关联。
回到我们原来的例子,我们的KeyedBroadcastProcessFunction可以是如下的样子。

new KeyedBroadcastProcessFunction<Color, Item, Rule, String>() {

    // store partial matches, i.e. first elements of the pair waiting for their second element
    // we keep a list as we may have many first elements waiting
    private final MapStateDescriptor<String, List<Item>> mapStateDesc =
        new MapStateDescriptor<>(
            "items",
            BasicTypeInfo.STRING_TYPE_INFO,
            new ListTypeInfo<>(Item.class));

    // identical to our ruleStateDescriptor above
    private final MapStateDescriptor<String, Rule> ruleStateDescriptor = 
        new MapStateDescriptor<>(
            "RulesBroadcastState",
            BasicTypeInfo.STRING_TYPE_INFO,
            TypeInformation.of(new TypeHint<Rule>() {}));

    @Override
    public void processBroadcastElement(Rule value,
                                        Context ctx,
                                        Collector<String> out) throws Exception {
        ctx.getBroadcastState(ruleStateDescriptor).put(value.name, value);
    }

    @Override
    public void processElement(Item value,
                               ReadOnlyContext ctx,
                               Collector<String> out) throws Exception {

        final MapState<String, List<Item>> state = getRuntimeContext().getMapState(mapStateDesc);
        final Shape shape = value.getShape();
    
        for (Map.Entry<String, Rule> entry :
                ctx.getBroadcastState(ruleStateDescriptor).immutableEntries()) {
            final String ruleName = entry.getKey();
            final Rule rule = entry.getValue();
    
            List<Item> stored = state.get(ruleName);
            if (stored == null) {
                stored = new ArrayList<>();
            }
    
            if (shape == rule.second && !stored.isEmpty()) {
                for (Item i : stored) {
                    out.collect("MATCH: " + i + " - " + value);
                }
                stored.clear();
            }
    
            // there is no else{} to cover if rule.first == rule.second
            if (shape.equals(rule.first)) {
                stored.add(value);
            }
    
            if (stored.isEmpty()) {
                state.remove(ruleName);
            } else {
                state.put(ruleName, stored);
            }
        }
    }
}

  

重要的考虑因素

 

在介绍完提供的API之后,本节重点介绍使用广播状态时需要注意的重要事项。这些事项是

  • 没有跨任务通信。如前所述,这就是为什么只有(Keyed)-BroadcastProcessFunction的广播端可以修改广播状态的内容的原因。此外,用户必须确保所有的任务对每一个传入元素都以同样的方式修改广播状态的内容。否则,不同的任务可能有不同的内容,导致结果不一致。
  • 不同任务的广播状态中事件的顺序可能不同。虽然广播流的元素保证了所有元素将(最终)进入所有下游任务,但元素可能会以不同的顺序到达每个任务。因此,每个传入元素的状态更新必须不依赖于传入事件的顺序。
  • 所有任务都会对其广播状态进行检查点。虽然当检查点发生时,所有任务的广播状态中都有相同的元素(检查点障碍不会超过元素),但所有任务都会检查点他们的广播状态,而不仅仅是其中一个。这是一个设计决定,以避免在还原过程中让所有任务从同一个文件中读取(从而避免热点),尽管它的代价是将检查点状态的大小增加了p的系数(=并行性)。Flink保证在恢复/缩放时,不会有重复和丢失的数据。在以相同或更小的并行度进行恢复的情况下,每个任务读取其检查点状态。扩容后,每个任务读取自己的状态,其余任务(p_new-p_old)以循环的方式读取之前任务的检查点。
  • 没有RocksDB状态后端。广播状态在运行时保存在内存中,内存供应也应相应进行。这对所有的操作者状态都适用。
posted @ 2021-01-03 17:32  田野与天  阅读(133)  评论(0编辑  收藏  举报