Flink處理函數實戰之三:KeyedProcessFunction類


歡迎訪問我的GitHub

https://github.com/zq2599/blog_demos

內容:所有原創文章分類匯總及配套源碼,涉及Java、Docker、Kubernetes、DevOPS等;

Flink處理函數實戰系列鏈接

  1. 深入了解ProcessFunction的狀態操作(Flink-1.10)
  2. ProcessFunction
  3. KeyedProcessFunction類
  4. ProcessAllWindowFunction(窗口處理)
  5. CoProcessFunction(雙流處理)

本篇概覽

本文是《Flink處理函數實戰》系列的第三篇,上一篇《Flink處理函數實戰之二:ProcessFunction類》學習了最簡單的ProcessFunction類,今天要了解的KeyedProcessFunction,以及該類帶來的一些特性;

關於KeyedProcessFunction

通過對比類圖可以確定,KeyedProcessFunction和ProcessFunction並無直接關系:
在這里插入圖片描述
KeyedProcessFunction用於處理KeyedStream的數據集合,相比ProcessFunction類,KeyedProcessFunction擁有更多特性,官方文檔如下圖紅框,狀態處理和定時器功能都是KeyedProcessFunction才有的:
在這里插入圖片描述
介紹完畢,接下來通過實例來學習吧;

版本信息

  1. 開發環境操作系統:MacBook Pro 13寸, macOS Catalina 10.15.3
  2. 開發工具:IDEA ULTIMATE 2018.3
  3. JDK:1.8.0_211
  4. Maven:3.6.0
  5. Flink:1.9.2

源碼下載

如果您不想寫代碼,整個系列的源碼可在GitHub下載到,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos):

名稱 鏈接 備注
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) git@github.com:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議

這個git項目中有多個文件夾,本章的應用在flinkstudy文件夾下,如下圖紅框所示:
在這里插入圖片描述

實戰簡介

本次實戰的目標是學習KeyedProcessFunction,內容如下:

  1. 監聽本機9999端口,獲取字符串;
  2. 將每個字符串用空格分隔,轉成Tuple2實例,f0是分隔后的單詞,f1等於1;
  3. 上述Tuple2實例用f0字段分區,得到KeyedStream;
  4. KeyedSteam轉入自定義KeyedProcessFunction處理;
  5. 自定義KeyedProcessFunction的作用,是記錄每個單詞最新一次出現的時間,然后建一個十秒的定時器,十秒后如果發現這個單詞沒有再次出現,就把這個單詞和它出現的總次數發送到下游算子;

編碼

  1. 繼續使用《Flink處理函數實戰之二:ProcessFunction類》一文中創建的工程flinkstudy;
  2. 創建bean類CountWithTimestamp,里面有三個字段,為了方便使用直接設為public:
package com.bolingcavalry.keyedprocessfunction;

public class CountWithTimestamp {
    public String key;

    public long count;

    public long lastModified;
}
  1. 創建FlatMapFunction的實現類Splitter,作用是將字符串分割后生成多個Tuple2實例,f0是分隔后的單詞,f1等於1:
package com.bolingcavalry;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;
import org.apache.flink.util.StringUtils;

public class Splitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
    @Override
    public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {

        if(StringUtils.isNullOrWhitespaceOnly(s)) {
            System.out.println("invalid line");
            return;
        }

        for(String word : s.split(" ")) {
            collector.collect(new Tuple2<String, Integer>(word, 1));
        }
    }
}
  1. 最后是整個邏輯功能的主體:ProcessTime.java,這里面有自定義的KeyedProcessFunction子類,還有程序入口的main方法,代碼在下面列出來之后,還會對關鍵部分做介紹:
package com.bolingcavalry.keyedprocessfunction;

import com.bolingcavalry.Splitter;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.watermark.Watermark;
import org.apache.flink.util.Collector;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @author will
 * @email zq2599@gmail.com
 * @date 2020-05-17 13:43
 * @description 體驗KeyedProcessFunction類(時間類型是處理時間)
 */
public class ProcessTime {

    /**
     * KeyedProcessFunction的子類,作用是將每個單詞最新出現時間記錄到backend,並創建定時器,
     * 定時器觸發的時候,檢查這個單詞距離上次出現是否已經達到10秒,如果是,就發射給下游算子
     */
    static class CountWithTimeoutFunction extends KeyedProcessFunction<Tuple, Tuple2<String, Integer>, Tuple2<String, Long>> {

        // 自定義狀態
        private ValueState<CountWithTimestamp> state;

        @Override
        public void open(Configuration parameters) throws Exception {
            // 初始化狀態,name是myState
            state = getRuntimeContext().getState(new ValueStateDescriptor<>("myState", CountWithTimestamp.class));
        }

        @Override
        public void processElement(
                Tuple2<String, Integer> value,
                Context ctx,
                Collector<Tuple2<String, Long>> out) throws Exception {

            // 取得當前是哪個單詞
            Tuple currentKey = ctx.getCurrentKey();

            // 從backend取得當前單詞的myState狀態
            CountWithTimestamp current = state.value();

            // 如果myState還從未沒有賦值過,就在此初始化
            if (current == null) {
                current = new CountWithTimestamp();
                current.key = value.f0;
            }

            // 單詞數量加一
            current.count++;

            // 取當前元素的時間戳,作為該單詞最后一次出現的時間
            current.lastModified = ctx.timestamp();

            // 重新保存到backend,包括該單詞出現的次數,以及最后一次出現的時間
            state.update(current);

            // 為當前單詞創建定時器,十秒后后觸發
            long timer = current.lastModified + 10000;

            ctx.timerService().registerProcessingTimeTimer(timer);

            // 打印所有信息,用於核對數據正確性
            System.out.println(String.format("process, %s, %d, lastModified : %d (%s), timer : %d (%s)\n\n",
                    currentKey.getField(0),
                    current.count,
                    current.lastModified,
                    time(current.lastModified),
                    timer,
                    time(timer)));

        }

        /**
         * 定時器觸發后執行的方法
         * @param timestamp 這個時間戳代表的是該定時器的觸發時間
         * @param ctx
         * @param out
         * @throws Exception
         */
        @Override
        public void onTimer(
                long timestamp,
                OnTimerContext ctx,
                Collector<Tuple2<String, Long>> out) throws Exception {

            // 取得當前單詞
            Tuple currentKey = ctx.getCurrentKey();

            // 取得該單詞的myState狀態
            CountWithTimestamp result = state.value();

            // 當前元素是否已經連續10秒未出現的標志
            boolean isTimeout = false;

            // timestamp是定時器觸發時間,如果等於最后一次更新時間+10秒,就表示這十秒內已經收到過該單詞了,
            // 這種連續十秒沒有出現的元素,被發送到下游算子
            if (timestamp == result.lastModified + 10000) {
                // 發送
                out.collect(new Tuple2<String, Long>(result.key, result.count));

                isTimeout = true;
            }

            // 打印數據,用於核對是否符合預期
            System.out.println(String.format("ontimer, %s, %d, lastModified : %d (%s), stamp : %d (%s), isTimeout : %s\n\n",
                    currentKey.getField(0),
                    result.count,
                    result.lastModified,
                    time(result.lastModified),
                    timestamp,
                    time(timestamp),
                    String.valueOf(isTimeout)));
        }
    }


    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // 並行度1
        env.setParallelism(1);

        // 處理時間
        env.setStreamTimeCharacteristic(TimeCharacteristic.ProcessingTime);

        // 監聽本地9999端口,讀取字符串
        DataStream<String> socketDataStream = env.socketTextStream("localhost", 9999);

        // 所有輸入的單詞,如果超過10秒沒有再次出現,都可以通過CountWithTimeoutFunction得到
        DataStream<Tuple2<String, Long>> timeOutWord = socketDataStream
                // 對收到的字符串用空格做分割,得到多個單詞
                .flatMap(new Splitter())
                // 設置時間戳分配器,用當前時間作為時間戳
                .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<Tuple2<String, Integer>>() {

                    @Override
                    public long extractTimestamp(Tuple2<String, Integer> element, long previousElementTimestamp) {
                        // 使用當前系統時間作為時間戳
                        return System.currentTimeMillis();
                    }

                    @Override
                    public Watermark getCurrentWatermark() {
                        // 本例不需要watermark,返回null
                        return null;
                    }
                })
                // 將單詞作為key分區
                .keyBy(0)
                // 按單詞分區后的數據,交給自定義KeyedProcessFunction處理
                .process(new CountWithTimeoutFunction());

        // 所有輸入的單詞,如果超過10秒沒有再次出現,就在此打印出來
        timeOutWord.print();

        env.execute("ProcessFunction demo : KeyedProcessFunction");
    }

    public static String time(long timeStamp) {
        return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date(timeStamp));
    }
}

上述代碼有幾處需要重點關注的:

  1. 通過assignTimestampsAndWatermarks設置時間戳的時候,getCurrentWatermark返回null,因為用不上watermark;
  2. processElement方法中,state.value()可以取得當前單詞的狀態,state.update(current)可以設置當前單詞的狀態,這個功能的詳情請參考《深入了解ProcessFunction的狀態操作(Flink-1.10)》
  3. registerProcessingTimeTimer方法設置了定時器的觸發時間,注意這里的定時器是基於processTime,和官方demo中的eventTime是不同的;
  4. 定時器觸發后,onTimer方法被執行,里面有這個定時器的全部信息,尤其是入參timestamp,這是原本設置的該定時器的觸發時間;

驗證

  1. 在控制台執行命令nc -l 9999,這樣就可以從控制台向本機的9999端口發送字符串了;
  2. 在IDEA上直接執行ProcessTime類的main方法,程序運行就開始監聽本機的9999端口了;
  3. 在前面的控制台輸入aaa,然后回車,等待十秒后,IEDA的控制台輸出以下信息,從結果可見符合預期:
    在這里插入圖片描述
  4. 繼續輸入aaa再回車,連續兩次,中間間隔不要超過10秒,結果如下圖,可見每一個Tuple2元素都有一個定時器,但是第二次輸入的aaa,其定時器在出發前,aaa的最新出現時間就被第三次輸入的操作給更新了,於是第二次輸入aaa的定時器中的對比操作發現此時距aaa的最近一次(即第三次)出現還未達到10秒,所以第二個元素不會發射到下游算子:
    在這里插入圖片描述
  5. 下游算子收到的所有超時信息會打印出來,如下圖紅框,只打印了數量等於1和3的記錄,等於2的時候因為在10秒內再次輸入了aaa,因此沒有超時接收,不會在下游打印:
    在這里插入圖片描述
    至此,KeyedProcessFunction處理函數的學習就完成了,其狀態讀寫和定時器操作都是很實用能力,希望本文可以給您提供參考;

你不孤單,欣宸原創一路相伴

  1. Java系列
  2. Spring系列
  3. Docker系列
  4. kubernetes系列
  5. 數據庫+中間件系列
  6. DevOps系列

歡迎關注公眾號:程序員欣宸

微信搜索「程序員欣宸」,我是欣宸,期待與您一同暢游Java世界...
https://github.com/zq2599/blog_demos


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM