• Window Join and CoGroup">Window Join and CoGroup
  • 小结">小结
  • 参考">参考

    在使用 Flink 进行实时数据处理时,一个常用的场景是对两个流的数据进行关联。这篇文章中我们将对双流操作的底层实现机制进行分析。

    Window Join and CoGroup

    Window Join 操作,顾名思义,是基于时间窗口对两个流进行关联操作。相比于 Join 操作, CoGroup 提供了一个更为通用的方式来处理两个流在相同的窗口内匹配的元素。 Join 复用了 CoGroup 的实现逻辑。它们的使用方式如下:

    | ``` stream.join(otherStream) .where() .equalTo() .window() .apply() stream.coGroup(otherStream) .where() .equalTo() .window() .apply()

    1. |
    2. | --- |
    3. `JoinFunction` `CogroupFunction` 接口的定义中可以大致看出它们的区别:
    4. |

    public interface JoinFunction extends Function, Serializable { /**

    1. * The join method, called once per joined pair of elements.
    2. *
    3. * @param first The element from first input.
    4. * @param second The element from second input.
    5. * @return The resulting element.
    6. *
    7. * @throws Exception This method may throw exceptions. Throwing an exception will cause the operation
    8. * to fail and may trigger recovery.
    9. */
    10. OUT join(IN1 first, IN2 second) throws Exception;

    } public interface CoGroupFunction extends Function, Serializable { /**

    1. * This method must be implemented to provide a user implementation of a
    2. * coGroup. It is called for each pair of element groups where the elements share the
    3. * same key.
    4. *
    5. * @param first The records from the first input.
    6. * @param second The records from the second.
    7. * @param out A collector to return elements.
    8. *
    9. * @throws Exception The function may throw Exceptions, which will cause the program to cancel,
    10. * and may trigger the recovery logic.
    11. */
    12. void coGroup(Iterable<IN1> first, Iterable<IN2> second, Collector<O> out) throws Exception;

    }

    1. |
    2. | --- |
    3. 可以看出来,`JoinFunction` 主要关注的是两个流中按照 key 匹配的每一对元素,而 `CoGroupFunction` 的参数则是两个中 key 相同的所有元素。`JoinFunction` 的逻辑更类似于 INNER JOIN,而 `CoGroupFunction` 除了可以实现 INNER JOIN,也可以实现 OUTER JOIN。<br />Window Join 的是被转换成 CoGroup 进行处理的:
    4. |

    public class JoinedStreams { public static class WithWindow { public DataStream apply(JoinFunction function, TypeInformation resultType) { //clean the closure function = input1.getExecutionEnvironment().clean(function); //Join 操作被转换为 CoGroup coGroupedWindowedStream = input1.coGroup(input2) .where(keySelector1) .equalTo(keySelector2) .window(windowAssigner) .trigger(trigger) .evictor(evictor) .allowedLateness(allowedLateness); //JoinFunction 被包装为 CoGroupFunction return coGroupedWindowedStream .apply(new JoinCoGroupFunction<>(function), resultType); } } /**

    1. * CoGroup function that does a nested-loop join to get the join result.
    2. */
    3. private static class JoinCoGroupFunction<T1, T2, T>
    4. extends WrappingFunction<JoinFunction<T1, T2, T>>
    5. implements CoGroupFunction<T1, T2, T> {
    6. private static final long serialVersionUID = 1L;
    7. public JoinCoGroupFunction(JoinFunction<T1, T2, T> wrappedFunction) {
    8. super(wrappedFunction);
    9. }
    10. @Override
    11. public void coGroup(Iterable<T1> first, Iterable<T2> second, Collector<T> out) throws Exception {
    12. for (T1 val1: first) {
    13. for (T2 val2: second) {
    14. //每一个匹配的元素对
    15. out.collect(wrappedFunction.join(val1, val2));
    16. }
    17. }
    18. }
    19. }

    }

    1. |
    2. | --- |
    3. 那么 CoGroup 又是怎么实现两个流的操作的呢?Flink 其实是通过一个变换,将两个流转换成一个流进行处理,转换之后数据流中的每一条消息都有一个标记来记录这个消息是属于左边的流还是右边的流,这样窗口的操作就和单个流的实现一样了。等到窗口被触发的时候,再按照标记将窗口内的元素分为左边的一组和右边的一组,然后交给 `CoGroupFunction` 进行处理。
    4. |

    public class CoGroupedStreams { public static class WithWindow { public DataStream apply(CoGroupFunction function, TypeInformation resultType) { //clean the closure function = input1.getExecutionEnvironment().clean(function); UnionTypeInfo unionType = new UnionTypeInfo<>(input1.getType(), input2.getType()); UnionKeySelector unionKeySelector = new UnionKeySelector<>(keySelector1, keySelector2); DataStream> taggedInput1 = input1 .map(new Input1Tagger()) .setParallelism(input1.getParallelism()) .returns(unionType); //左边流 DataStream> taggedInput2 = input2 .map(new Input2Tagger()) .setParallelism(input2.getParallelism()) .returns(unionType); //右边流

    1. //合并成一个数据流
    2. DataStream<TaggedUnion<T1, T2>> unionStream = taggedInput1.union(taggedInput2);
    3. // we explicitly create the keyed stream to manually pass the key type information in
    4. windowedStream =
    5. new KeyedStream<TaggedUnion<T1, T2>, KEY>(unionStream, unionKeySelector, keyType)
    6. .window(windowAssigner);
    7. if (trigger != null) {
    8. windowedStream.trigger(trigger);
    9. }
    10. if (evictor != null) {
    11. windowedStream.evictor(evictor);
    12. }
    13. if (allowedLateness != null) {
    14. windowedStream.allowedLateness(allowedLateness);
    15. }
    16. return windowedStream.apply(new CoGroupWindowFunction<T1, T2, T, KEY, W>(function), resultType);
    17. }
    18. }
    19. //将 CoGroupFunction 封装为 WindowFunction
    20. private static class CoGroupWindowFunction<T1, T2, T, KEY, W extends Window>
    21. extends WrappingFunction<CoGroupFunction<T1, T2, T>>
    22. implements WindowFunction<TaggedUnion<T1, T2>, T, KEY, W> {
    23. private static final long serialVersionUID = 1L;
    24. public CoGroupWindowFunction(CoGroupFunction<T1, T2, T> userFunction) {
    25. super(userFunction);
    26. }
    27. @Override
    28. public void apply(KEY key,
    29. W window,
    30. Iterable<TaggedUnion<T1, T2>> values,
    31. Collector<T> out) throws Exception {
    32. List<T1> oneValues = new ArrayList<>();
    33. List<T2> twoValues = new ArrayList<>();
    34. //窗口内的所有元素按标记重新分为左边的一组和右边的一组
    35. for (TaggedUnion<T1, T2> val: values) {
    36. if (val.isOne()) {
    37. oneValues.add(val.getOne());
    38. } else {
    39. twoValues.add(val.getTwo());
    40. }
    41. }
    42. //调用 CoGroupFunction
    43. wrappedFunction.coGroup(oneValues, twoValues, out);
    44. }
    45. }

    }

    1. |
    2. | --- |
    3. <a name="connected-streams"></a>
    4. ## [](https://blog.jrwang.me/2019/flink-source-code-two-stream-join/#connected-streams)Connected Streams
    5. Window Join 可以方便地对两个数据流进行关联操作。但有些使用场景中,我们需要的并非关联操作,`ConnectedStreams` 提供了更为通用的双流操作。<br />`ConnectedStreams` 配合 `CoProcessFunction` `KeyedCoProcessFunction` 使用,`KeyedCoProcessFunction` 要求连接的两个 stream 都是 `KeyedStream`,并且 key 的类型一致。<br />`ConnectedStreams` 配合 `CoProcessFunction` 生成 `CoProcessOperator`,在运行时被调度为 `TwoInputStreamTask`,从名字也可以看书来,这个 Task 处理的是两个输入。`TwoInputStreamTask` 在前面关于 Task 的生命周期的文章中已经进行了介绍。我们简单看一下 `CoProcessOperator` 的实现:
    6. |

    public class CoProcessOperator extends AbstractUdfStreamOperator> implements TwoInputStreamOperator { @Override public void processElement1(StreamRecord element) throws Exception { collector.setTimestamp(element); context.element = element; userFunction.processElement1(element.getValue(), context, collector); context.element = null; } @Override public void processElement2(StreamRecord element) throws Exception { collector.setTimestamp(element); context.element = element; userFunction.processElement2(element.getValue(), context, collector); context.element = null; } }

    1. |
    2. | --- |
    3. `CoProcessOperator` 内部区分了两个流的处理,分别调用 `CoProcessFunction.processElement1()` `userFunction.processElement2()` 进行处理。对于 `KeyedCoProcessOperator` 也是类似的机制。<br />通过内部的共享状态,可以在双流上实现很多复杂的操作。接下来我们就介绍 Flink 基于 Connected Streams 实现的另一种双流关联操作 - Interval Join
    4. <a name="interval-join"></a>
    5. ## [](https://blog.jrwang.me/2019/flink-source-code-two-stream-join/#interval-join)Interval Join
    6. Window Join 的一个局限是关联的两个数据流必须在同样的时间窗口中。但有些时候,我们希望在一个数据流中的消息到达时,在另一个数据流的一段时间内去查找匹配的元素。更确切地说,如果数据流 b 中消息到达时,我们希望在数据流 a 中匹配的元素的时间范围为 `a.timestamp + lowerBound <= b.timestamp <= a.timestamp + upperBound`;同样,对数据流 a 中的消息也是如此。在这种情况,就可以使用 Interval Join。具体的用法如下:
    7. |

    stream .keyBy() .intervalJoin(otherStream.keyBy()) .between(

    1. |
    2. | --- |
    3. Interval Join 是基于 `ConnectedStreams` 实现的:
    4. |

    public class KeyedStream extends DataStream { public static class IntervalJoined { public SingleOutputStreamOperator process( ProcessJoinFunction processJoinFunction, TypeInformation outputType) { Preconditions.checkNotNull(processJoinFunction); Preconditions.checkNotNull(outputType); final ProcessJoinFunction cleanedUdf = left.getExecutionEnvironment().clean(processJoinFunction); final IntervalJoinOperator operator = new IntervalJoinOperator<>( lowerBound, upperBound, lowerBoundInclusive, upperBoundInclusive, left.getType().createSerializer(left.getExecutionConfig()), right.getType().createSerializer(right.getExecutionConfig()), cleanedUdf ); return left .connect(right) .keyBy(keySelector1, keySelector2) .transform(“Interval Join”, outputType, operator); } } }

    1. |
    2. | --- |
    3. `IntervalJoinOperator` 中,使用两个 MapState 分别保存两个数据流到达的消息,MapState key 是消息的时间。当一个数据流有新消息到达时,就会去另一个数据流的状态中查找时间落在匹配范围内的消息,然后进行关联处理。每一条消息会注册一个定时器,在时间越过该消息的有效范围后从状态中清除该消息。
    4. |

    public class IntervalJoinOperator extends AbstractUdfStreamOperator> implements TwoInputStreamOperator, Triggerable {

    1. private transient MapState<Long, List<BufferEntry<T1>>> leftBuffer;
    2. private transient MapState<Long, List<BufferEntry<T2>>> rightBuffer;
    3. @Override
    4. public void processElement1(StreamRecord<T1> record) throws Exception {
    5. processElement(record, leftBuffer, rightBuffer, lowerBound, upperBound, true);
    6. }
    7. @Override
    8. public void processElement2(StreamRecord<T2> record) throws Exception {
    9. processElement(record, rightBuffer, leftBuffer, -upperBound, -lowerBound, false);
    10. }
    11. private <THIS, OTHER> void processElement(
    12. final StreamRecord<THIS> record,
    13. final MapState<Long, List<IntervalJoinOperator.BufferEntry<THIS>>> ourBuffer,
    14. final MapState<Long, List<IntervalJoinOperator.BufferEntry<OTHER>>> otherBuffer,
    15. final long relativeLowerBound,
    16. final long relativeUpperBound,
    17. final boolean isLeft) throws Exception {
    18. final THIS ourValue = record.getValue();
    19. final long ourTimestamp = record.getTimestamp();
    20. if (ourTimestamp == Long.MIN_VALUE) {
    21. throw new FlinkException("Long.MIN_VALUE timestamp: Elements used in " +
    22. "interval stream joins need to have timestamps meaningful timestamps.");
    23. }
    24. if (isLate(ourTimestamp)) {
    25. return;
    26. }
    27. //将消息加入状态中
    28. addToBuffer(ourBuffer, ourValue, ourTimestamp);
    29. //从另一个数据流的状态中查找匹配的记录
    30. for (Map.Entry<Long, List<BufferEntry<OTHER>>> bucket: otherBuffer.entries()) {
    31. final long timestamp = bucket.getKey();
    32. if (timestamp < ourTimestamp + relativeLowerBound ||
    33. timestamp > ourTimestamp + relativeUpperBound) {
    34. continue;
    35. }
    36. for (BufferEntry<OTHER> entry: bucket.getValue()) {
    37. if (isLeft) {
    38. collect((T1) ourValue, (T2) entry.element, ourTimestamp, timestamp);
    39. } else {
    40. collect((T1) entry.element, (T2) ourValue, timestamp, ourTimestamp);
    41. }
    42. }
    43. }
    44. //注册清理状态的timer
    45. long cleanupTime = (relativeUpperBound > 0L) ? ourTimestamp + relativeUpperBound : ourTimestamp;
    46. if (isLeft) {
    47. internalTimerService.registerEventTimeTimer(CLEANUP_NAMESPACE_LEFT, cleanupTime);
    48. } else {
    49. internalTimerService.registerEventTimeTimer(CLEANUP_NAMESPACE_RIGHT, cleanupTime);
    50. }
    51. }

    } ``` | | —- |

    小结

    双流操作是实时计算场景下经常用到的操作。相比于单个数据流上的操作,双流操作要同时考虑到两个数据流中数据的关联性,因而要更为复杂一些。本文简单介绍了在 Flink 中对双流操作的实现机制,包括 Join 操作、CoGroup 操作和 Connected Streams 等。Connected Streams 提供了更为通用的处理两个数据流的方法,特别适用于一个数据流的消息会对另一个数据流的消息处理产生影响的场景,但这通常也要依赖于内部的共享状态。

    参考

    -EOF-