Flink专题

Flink Streaming广播状态模式(The Broadc

2019-02-11  本文已影响108人  尼小摩

Working with State描述了运算符状态,该状态在恢复时均匀分布于运算符的并行任务之间,或unioned,使用整个状态初始化恢复的并行任务。

Flink支持的第三种操作符状态是广播状态(Broadcast State)。广播状态(Broadcast State)的引入是为了支持一些来自一个流的数据需要广播到所有下游任务的情况,它存储在本地,用于处理其他流上的所有传入元素。例如,广播状态可以作为一种自然匹配出现,您可以想象一个低吞吐量流,其中包含一组规则,我们希望对来自另一个流的所有元素进行评估。考虑到上述类型的情况,broadcast状态与其他运算符状态的不同之处在于:

  1. 它有一种Map格式。
  2. 它仅对具有广播流和非广播流作为输入的特定操作符可用。
  3. 并且这样的操作符可以有不同名称的多个广播状态。

Provided APIs

为了展示所提供的api,在展示其全部功能之前,我们将从一个示例开始。作为我们的运行示例,我们会用到这样的例子,有一个不同颜色和形状的对象流,我们想要遵循一定的模式找到一对相同颜色的对象,
长方形后面跟一个三角形,我们假设这组有趣的模式会随着时间而发展。

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

从Items流开始,因为我们想要相同颜色的对,只需要按颜色key分组,这将确保相同颜色的元素最终出现在相同的物理机器上。

// key the shapes by color
KeyedStream<Item, Color> colorPartitionedStream = shapeStream
                        .keyBy(new KeySelector<Shape, 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);

最后,为了对来自项目流的输入元素评估规则,我们需要:

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

将流(键或非键)与广播流连接,可在非广播流上调用connect(),以BroadcastStream为参数。将返回一个BroadcastConnectedStream,在它上面我们可以使用一种特殊类型的CoProcessFunction调用process()。该函数将包含我们的匹配逻辑。函数的确切类型取决于非广播流的类型:

假设我们的非广播流是键的,以下片段包括上述调用:
应该在非广播流上调用连接,并将广播流作为参数。

DataStream<Match> 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)中的状态描述符相同。

不同之处在于它们对广播状态的访问类型。广播端具有读写访问权,而非广播端具有只读访问权(即名称)。原因是在Flink中没有跨任务通信。为了保证广播状态下的内容在运算符的所有并行实例中都是相同的,我们只对广播端提供读写访问,它在所有任务中看到相同的元素,我们要求在这一侧的每个传入元素上的计算在所有任务中都是相同的。忽略此规则将破坏状态的一致性保证,导致不一致且通常难以调试结果。

注意:在“processBroadcast()”中实现的逻辑必须在所有并行实例中具有相同的确定性行为!

最后,由于KeyedBroadcastProcessFunction是在一个键流上操作的,它公开了一些BroadcastProcessFunction不可用的功能。那就是:

  1. processElement()方法中的ReadOnlyContext允许访问Flink的底层计时器服务,允许注册事件和/或处理时间计时器。当计时器触发时,onTimer()(如上所示)通过OnTimerContext调用,OnTimerContext公开了与ReadOnlyContext plus相同的功能
  1. processBroadcastElement()方法中的上下文包含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之后,本节将重点介绍在使用broadcast state时需要记住的重要内容。

上一篇 下一篇

猜你喜欢

热点阅读