Flink實戰(七) - Time & Windows程式設計

一生只為虞美人發表於2019-07-23

0 相關原始碼

掌握Flink中三種常用的Time處理方式,掌握Flink中滾動視窗以及滑動視窗的使用,瞭解Flink中的watermark。

Flink 在流處理工程中支援不同的時間概念。

1 處理時間(Processing time)

執行相應運算元操作的機器的系統時間.

當流程式在處理時間執行時,所有基於時間的 運算元操作(如時間視窗)將使用執行相應運算元的機器的系統時鐘。每小時處理時間視窗將包括在系統時鐘指示整個小時之間到達特定運算元的所有記錄。

例如,如果應用程式在上午9:15開始執行,則第一個每小時處理時間視窗將包括在上午9:15到上午10:00之間處理的事件,下一個視窗將包括在上午10:00到11:00之間處理的事件

處理時間是最簡單的時間概念,不需要流和機器之間的協調

它提供最佳效能和最低延遲。但是,在分散式和非同步環境中,處理時間不提供確定性,因為它容易受到記錄到達系統的速度(例如從訊息佇列)到記錄在系統內的運算元之間流動的速度的影響。和停電(排程或其他)。

2 事件時間(Event time)

每個單獨的事件在其生產裝置上發生的時間.

此時間通常在進入Flink之前內建在記錄中,並且可以從每個記錄中提取該事件時間戳。

在事件時間,時間的進展取決於資料,而不是任何掛鐘。

事件時間程式必須指定如何生成事件時間水印,這是表示事件時間進度的機制.

在一個完美的世界中,事件時間處理將產生完全一致和確定的結果,無論事件何時到達,或者順序.

但是,除非事件已知按順序到達(按時間戳),否則事件時間處理會在等待無序事件時產生一些延遲。由於只能等待一段有限的時間,因此限制了確定性事件時間應用程式的可能性。

假設所有資料都已到達,運算元操作將按預期執行,即使在處理無序或延遲事件或重新處理歷史資料時也會產生正確且一致的結果。

例如,每小時事件時間視窗將包含帶有落入該小時的事件時間戳的所有記錄,無論它們到達的順序如何,或者何時處理它們。(有關更多資訊,請參閱有關遲發事件的部分。)

請注意,有時當事件時間程式實時處理實時資料時,它們將使用一些處理時間 運算元操作,以確保它們及時進行。

3 攝取時間(Ingestion time)

事件進入Flink的時間.

在源運算元處,每個記錄將源的當前時間作為時間戳,並且基於時間的運算元操作(如時間視窗)引用該時間戳。

在概念上位於事件時間處理時間之間。

  • 與處理時間相比 ,它成本稍微高一些,但可以提供更可預測的結果。因為使用穩定的時間戳(在源處分配一次),所以對記錄的不同視窗 運算元操作將引用相同的時間戳,而在處理時間中,每個視窗運算元可以將記錄分配給不同的視窗(基於本地系統時鐘和任何運輸延誤)
  • 與事件時間相比,無法處理任何無序事件或後期資料,但程式不必指定如何生成水印。

在內部,攝取時間與事件時間非常相似,但具有自動時間戳分配和自動水印生成函式

Flink實戰(七) - Time & Windows程式設計

4 設定時間特性

Flink DataStream程式的第一部分通常設定基本時間特性

Flink實戰(七) - Time & Windows程式設計

  • 顯然,在Flink的流式處理環境中,預設使用處理時間Flink實戰(七) - Time & Windows程式設計

該設定定義了資料流源的行為方式(例如,它們是否將分配時間戳),以及視窗 運算元操作應該使用的時間概念,比如

KeyedStream.timeWindow(Time.seconds(30))。

以下示例顯示了一個Flink程式,該程式在每小時時間視窗中聚合事件。視窗的行為適應時間特徵。

  • Java
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

// 可選的:
// env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime);
// env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

DataStream<MyEvent> stream = env.addSource(new FlinkKafkaConsumer09<MyEvent>(topic, schema, props));

stream
    .keyBy( (event) -> event.getUser() )
    .timeWindow(Time.hours(1))
    .reduce( (a, b) -> a.add(b) )
    .addSink(...);
  • Scala
val env = StreamExecutionEnvironment.getExecutionEnvironment

env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime)

// alternatively:
// env.setStreamTimeCharacteristic(TimeCharacteristic.IngestionTime)
// env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)

val stream: DataStream[MyEvent] = env.addSource(new FlinkKafkaConsumer09[MyEvent](topic, schema, props))

stream
    .keyBy( _.getUser )
    .timeWindow(Time.hours(1))
    .reduce( (a, b) => a.add(b) )
    .addSink(...)

請注意,為了在事件時間執行此示例,程式需要使用直接為資料定義事件時間的源並自行發出水印,或者程式必須在源之後注入時間戳分配器和水印生成器。這些函式描述瞭如何訪問事件時間戳,以及事件流表現出的無序程度。

5 Windows

5.1 簡介

Windows是處理無限流的核心。Windows將流拆分為有限大小的“桶”,我們可以在其上應用計算。我們重點介紹如何在Flink中執行視窗,以及程式設計師如何從其提供的函式中獲益最大化。

視窗Flink程式的一般結構如下所示

  • 第一個片段指的是被Keys化流
  • 而第二個片段指的是非被Keys化流

正如所看到的,唯一的區別是keyBy(...)呼籲Keys流和window(...)成為windowAll(...)非被Key化的資料流。這也將作為頁面其餘部分的路線圖。

Keyed Windows

Flink實戰(七) - Time & Windows程式設計

Non-Keyed Windows

Flink實戰(七) - Time & Windows程式設計

在上面,方括號(...)中的命令是可選的。這表明Flink允許您以多種不同方式自定義視窗邏輯,以便最適合您的需求。

5.2 視窗生命週期

簡而言之,只要應該屬於此視窗的第一個資料元到達,就會建立一個視窗,當時間(事件或處理時間)超過其結束時間戳加上使用者指定 時,視窗將被完全刪除allowed lateness(請參閱允許的延遲))。Flink保證僅刪除基於時間的視窗而不是其他型別,例如全域性視窗(請參閱視窗分配器)。例如,使用基於事件時間的視窗策略,每5分鐘建立一個非重疊(或翻滾)的視窗,並允許延遲1分鐘,Flink將建立一個新視窗,用於間隔12:00和12:05當具有落入此間隔的時間戳的第一個資料元到達時,當水印通過12:06 時間戳時它將刪除它。

此外,每個視窗將具有Trigger和一個函式(ProcessWindowFunction,ReduceFunction, AggregateFunction或FoldFunction)連線到它。該函式將包含要應用於視窗內容的計算,而Trigger指定視窗被認為準備好應用該函式的條件。

觸發策略可能類似於“當視窗中的資料元數量大於4”時,或“當水印通過視窗結束時”。

觸發器還可以決定在建立和刪除之間的任何時間清除視窗的內容。在這種情況下,清除僅指視窗中的資料元,而不是視窗後設資料。這意味著仍然可以將新資料新增到該視窗。

除了上述內容之外,您還可以指定一個Evictor,它可以在觸發器觸發後以及應用函式之前和/或之後從視窗中刪除資料元。

5.3 被Keys化與非被Keys化Windows

要指定的第一件事是您的流是否應該鍵入。必須在定義視窗之前完成此 運算元操作。使用the keyBy(...)將您的無限流分成邏輯被Key化的資料流。如果keyBy(...)未呼叫,則表示您的流不是被Keys化的。

對於被Key化的資料流,可以將傳入事件的任何屬性用作鍵(此處有更多詳細資訊)。擁有被Key化的資料流將允許您的視窗計算由多個任務並行執行,因為每個邏輯被Key化的資料流可以獨立於其餘任務進行處理。引用相同Keys的所有資料元將被髮送到同一個並行任務。

在非被Key化的資料流的情況下,您的原始流將不會被拆分為多個邏輯流,並且所有視窗邏輯將由單個任務執行,即並行度為1。

6 視窗分配器

指定流是否已鍵入後,下一步是定義一個視窗分配器.

視窗分配器定義如何將資料元分配給視窗,這是通過WindowAssigner 在window(...)(對於被Keys化流)或windowAll()(對於非被Keys化流)呼叫中指定您的選擇來完成的

Flink實戰(七) - Time & Windows程式設計

WindowAssigner負責將每個傳入資料元分配給一個或多個視窗

Flink帶有預定義的視窗分配器,用於最常見的用例,即

  • 滾動視窗
  • 滑動視窗
  • 會話視窗
  • 全域性視窗

還可以通過擴充套件WindowAssigner類來實現自定義視窗分配器。所有內建視窗分配器(全域性視窗除外)都根據時間為視窗分配資料元,這可以是處理時間或事件時間。請檢視我們關於活動時間的部分,瞭解處理時間和事件時間之間的差異以及時間戳和水印的生成方式。

基於時間的視窗具有開始時間戳(包括)和結束時間戳(不包括),它們一起描述視窗的大小。

在程式碼中,Flink在使用TimeWindow基於時間的視窗時使用,該視窗具有查詢開始和結束時間戳的方法maxTimestamp()返回給定視窗的最大允許時間戳

Flink實戰(七) - Time & Windows程式設計

下圖顯示了每個分配者的工作情況。紫色圓圈表示流的資料元,這些資料元由某個鍵(在這種情況下是使用者1,使用者2和使用者3)劃分。x軸顯示時間的進度。

6.1 滾動視窗

一個滾動視窗分配器的每個資料元分配給指定的視窗的視窗大小。滾動視窗具有固定的尺寸,不重疊.

例如,如果指定大小為5分鐘的翻滾視窗,則將評估當前視窗,並且每五分鐘將啟動一個新視窗,如下圖所示

Flink實戰(七) - Time & Windows程式設計

以下程式碼段顯示瞭如何使用滾動視窗。

  • Java
DataStream<T> input = ...;

// tumbling event-time windows
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>);

// tumbling processing-time windows
input
    .keyBy(<key selector>)
    .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>);

// daily tumbling event-time windows offset by -8 hours.
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.days(1), Time.hours(-8)))
    .<windowed transformation>(<window function>);
  • Scala
val input: DataStream[T] = ...

// tumbling event-time windows
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>)

// tumbling processing-time windows
input
    .keyBy(<key selector>)
    .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>)

// daily tumbling event-time windows offset by -8 hours.
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.days(1), Time.hours(-8)))
    .<windowed transformation>(<window function>)
  • Scala
    Flink實戰(七) - Time & Windows程式設計
  • Java
    Flink實戰(七) - Time & Windows程式設計

6.2 滑動視窗

該滑動視窗分配器分配元件以固定長度的視窗。與滾動視窗分配器類似,視窗大小由視窗大小引數配置

附加的視窗滑動引數控制滑動視窗的啟動頻率。因此,如果幻燈片小於視窗大小,則滑動視窗可以重疊。在這種情況下,資料元被分配給多個視窗。

例如,您可以將大小為10分鐘的視窗滑動5分鐘。有了這個,你每隔5分鐘就會得到一個視窗,其中包含過去10分鐘內到達的事件,如下圖所示。

Flink實戰(七) - Time & Windows程式設計

以下程式碼段顯示瞭如何使用滑動視窗

  • Java
DataStream<T> input = ...;

// 滑動 事件時間 視窗
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>);

//  滑動 處理時間 視窗
input
    .keyBy(<key selector>)
    .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>);

// daily tumbling event-time windows offset by -8 hours.
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.days(1), Time.hours(-8)))
    .<windowed transformation>(<window function>);
  • Scala
val input: DataStream[T] = ...

// tumbling event-time windows
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>)

// tumbling processing-time windows
input
    .keyBy(<key selector>)
    .window(TumblingProcessingTimeWindows.of(Time.seconds(5)))
    .<windowed transformation>(<window function>)

// daily tumbling event-time windows offset by -8 hours.
input
    .keyBy(<key selector>)
    .window(TumblingEventTimeWindows.of(Time.days(1), Time.hours(-8)))
    .<windowed transformation>(<window function>)

7 視窗函式

定義視窗分配器後,我們需要指定要在每個視窗上執行的計算。這是視窗函式的職責,視窗函式用於在系統確定視窗準備好進行處理後處理每個(可能是被Keys化的)視窗的資料元

的窗函式可以是一個ReduceFunction,AggregateFunction,FoldFunction或ProcessWindowFunction。前兩個可以更有效地執行,因為Flink可以在每個視窗到達時遞增地聚合它們的資料元.

ProcessWindowFunction獲取Iterable視窗中包含的所有資料元以及有關資料元所屬視窗的其他元資訊。

具有ProcessWindowFunction的視窗轉換不能像其他情況一樣有效地執行,因為Flink必須在呼叫函式之前在內部緩衝視窗的所有資料元。這可以通過組合來減輕ProcessWindowFunction與ReduceFunction,AggregateFunction或FoldFunction以獲得兩個視窗元件的增量聚合並且該附加後設資料視窗 ProcessWindowFunction接收。我們將檢視每個變體的示例。

7.1 ReduceFunction

指定如何組合輸入中的兩個資料元以生成相同型別的輸出資料元.

Flink使用ReduceFunction來遞增地聚合視窗的資料元.

定義和使用

  • Java
DataStream<Tuple2<String, Long>> input = ...;

input
    .keyBy(<key selector>)
    .window(<window assigner>)
    .reduce(new ReduceFunction<Tuple2<String, Long>> {
      public Tuple2<String, Long> reduce(Tuple2<String, Long> v1, Tuple2<String, Long> v2) {
        return new Tuple2<>(v1.f0, v1.f1 + v2.f1);
      }
    });
  • Scala
val input: DataStream[(String, Long)] = ...

input
    .keyBy(<key selector>)
    .window(<window assigner>)
    .reduce { (v1, v2) => (v1._1, v1._2 + v2._2) }

原來傳遞進來的資料是字串,此處我們就使用數值型別,通過數值型別來演示增量的效果

這裡不是等待視窗所有的資料進行一次性處理,而是資料兩兩處理

Flink實戰(七) - Time & Windows程式設計

  • 輸入
    Flink實戰(七) - Time & Windows程式設計
  • 增量輸出
    Flink實戰(七) - Time & Windows程式設計
  • Java
    Flink實戰(七) - Time & Windows程式設計7.2 聚合函式An AggregateFunction是一個通用版本,ReduceFunction它有三種型別:輸入型別(IN),累加器型別(ACC)和輸出型別(OUT)。輸入型別是輸入流中資料元的型別,並且AggregateFunction具有將一個輸入資料元新增到累加器的方法。該介面還具有用於建立初始累加器的方法,用於將兩個累加器合併到一個累加器中以及用於OUT從累加器提取輸出(型別)。我們將在下面的示例中看到它的工作原理。

與之相同ReduceFunction,Flink將在視窗到達時遞增地聚合視窗的輸入資料元。

一個AggregateFunction可以被定義並這樣使用:

/**
 * The accumulator is used to keep a running sum and a count. The {@code getResult} method
 * computes the average.
 */
private static class AverageAggregate
    implements AggregateFunction<Tuple2<String, Long>, Tuple2<Long, Long>, Double> {
  @Override
  public Tuple2<Long, Long> createAccumulator() {
    return new Tuple2<>(0L, 0L);
  }

  @Override
  public Tuple2<Long, Long> add(Tuple2<String, Long> value, Tuple2<Long, Long> accumulator) {
    return new Tuple2<>(accumulator.f0 + value.f1, accumulator.f1 + 1L);
  }

  @Override
  public Double getResult(Tuple2<Long, Long> accumulator) {
    return ((double) accumulator.f0) / accumulator.f1;
  }

  @Override
  public Tuple2<Long, Long> merge(Tuple2<Long, Long> a, Tuple2<Long, Long> b) {
    return new Tuple2<>(a.f0 + b.f0, a.f1 + b.f1);
  }
}

DataStream<Tuple2<String, Long>> input = ...;

input
    .keyBy(<key selector>)
    .window(<window assigner>)
    .aggregate(new AverageAggregate());
  • Scala
The accumulator is used to keep a running sum and a count. The [getResult] method
 \* computes the average.
 \*/
class AverageAggregate extends AggregateFunction[(String, Long), (Long, Long), Double] {
  override def createAccumulator() = (0L, 0L)

  override def add(value: (String, Long), accumulator: (Long, Long)) =
    (accumulator.\_1 + value.\_2, accumulator.\_2 + 1L)

  override def getResult(accumulator: (Long, Long)) = accumulator.\_1 / accumulator.\_2

  override def merge(a: (Long, Long), b: (Long, Long)) =
    (a.\_1 + b.\_1, a.\_2 + b.\_2)
}

val input: DataStream[(String, Long)] = ...

input
    .keyBy(<key selector>)
    .window(<window assigner>)
    .aggregate(new AverageAggregate)

7.3 ProcessWindowFunction

ProcessWindowFunction獲取包含視窗的所有資料元的Iterable,以及可訪問時間和狀態資訊的Context物件,這使其能夠提供比其他視窗函式更多的靈活性。這是以效能和資源消耗為代價的,因為資料元不能以遞增方式聚合,而是需要在內部進行緩衝,直到視窗被認為已準備好進行處理。

ProcessWindowFunction外觀簽名如下:

public abstract class ProcessWindowFunction<IN, OUT, KEY, W extends Window> implements Function {

    /**
     * Evaluates the window and outputs none or several elements.
     *
     * @param key The key for which this window is evaluated.
     * @param context The context in which the window is being evaluated.
     * @param elements The elements in the window being evaluated.
     * @param out A collector for emitting elements.
     *
     * @throws Exception The function may throw exceptions to fail the program and trigger recovery.
     */
    public abstract void process(
            KEY key,
            Context context,
            Iterable<IN> elements,
            Collector<OUT> out) throws Exception;

    /**
     * The context holding window metadata.
     */
    public abstract class Context implements java.io.Serializable {
        /**
         * Returns the window that is being evaluated.
         */
        public abstract W window();

        /** Returns the current processing time. */
        public abstract long currentProcessingTime();

        /** Returns the current event-time watermark. */
        public abstract long currentWatermark();

        /**
         * State accessor for per-key and per-window state.
         *
         * <p><b>NOTE:</b>If you use per-window state you have to ensure that you clean it up
         * by implementing {@link ProcessWindowFunction#clear(Context)}.
         */
        public abstract KeyedStateStore windowState();

        /**
         * State accessor for per-key global state.
         */
        public abstract KeyedStateStore globalState();
    }

}
abstract class ProcessWindowFunction[IN, OUT, KEY, W <: Window] extends Function {

  /**
    * Evaluates the window and outputs none or several elements.
    *
    * @param key      The key for which this window is evaluated.
    * @param context  The context in which the window is being evaluated.
    * @param elements The elements in the window being evaluated.
    * @param out      A collector for emitting elements.
    * @throws Exception The function may throw exceptions to fail the program and trigger recovery.
    */
  def process(
      key: KEY,
      context: Context,
      elements: Iterable[IN],
      out: Collector[OUT])

  /**
    * The context holding window metadata
    */
  abstract class Context {
    /**
      * Returns the window that is being evaluated.
      */
    def window: W

    /**
      * Returns the current processing time.
      */
    def currentProcessingTime: Long

    /**
      * Returns the current event-time watermark.
      */
    def currentWatermark: Long

    /**
      * State accessor for per-key and per-window state.
      */
    def windowState: KeyedStateStore

    /**
      * State accessor for per-key global state.
      */
    def globalState: KeyedStateStore
  }

}

該key引數是通過KeySelector為keyBy()呼叫指定的Keys提取的Keys。在元組索引鍵或字串欄位引用的情況下,此鍵型別始終是Tuple,您必須手動將其轉換為正確大小的元組以提取鍵欄位。

A ProcessWindowFunction可以像這樣定義和使用:

DataStream<Tuple2<String, Long>> input = ...;

input
  .keyBy(t -> t.f0)
  .timeWindow(Time.minutes(5))
  .process(new MyProcessWindowFunction());

/* ... */

public class MyProcessWindowFunction
    extends ProcessWindowFunction<Tuple2<String, Long>, String, String, TimeWindow> {

  @Override
  public void process(String key, Context context, Iterable<Tuple2<String, Long>> input, Collector<String> out) {
    long count = 0;
    for (Tuple2<String, Long> in: input) {
      count++;
    }
    out.collect("Window: " + context.window() + "count: " + count);
  }
}
val input: DataStream[(String, Long)] = ...

input
  .keyBy(_._1)
  .timeWindow(Time.minutes(5))
  .process(new MyProcessWindowFunction())

/* ... */

class MyProcessWindowFunction extends ProcessWindowFunction[(String, Long), String, String, TimeWindow] {

  def process(key: String, context: Context, input: Iterable[(String, Long)], out: Collector[String]): () = {
    var count = 0L
    for (in <- input) {
      count = count + 1
    }
    out.collect(s"Window ${context.window} count: $count")
  }
}

該示例顯示了ProcessWindowFunction對視窗中的資料元進行計數的情況。此外,視窗函式將有關視窗的資訊新增到輸出。

注意注意,使用ProcessWindowFunction簡單的聚合(例如count)是非常低效的

Flink實戰(七) - Time & Windows程式設計

8 水印

參考

Event Time

Windows

相關文章