數據大盤-搜索詞統計(KeyedProcessFunction)

0.需求

實時輸出當天的搜索詞排名,即實時呈現熱點搜索詞

1.數據源讀取

對接Kafka數據源,將消息轉成實體類(實體類屬性主要是關鍵詞和搜索時間)

public class KafkaUtil {

    public static FlinkKafkaConsumerBase<String> text(String topic) throws IOException {
        return text(topic, "kafka.properties");
    }

    /**
     * @param topic 主題名稱
     * @param configPath Kafka屬性配置文件路徑
     */
    public static FlinkKafkaConsumerBase<String> text(String topic,String configPath) throws IOException {

        //1.加載Kafka屬性
        Properties prop=new Properties();
        //Class.getClassLoader.getResourceAsStream 默認是從ClassPath根下獲取,path不能以“/"開頭
        InputStream in=KafkaUtil.class.getClassLoader().getResourceAsStream(configPath);
        prop.load(in);
        //2.構造FlinkKafkaConsumer
        FlinkKafkaConsumerBase<String> consumer=new FlinkKafkaConsumer011<>(topic,new SimpleStringSchema(),prop);
        //todo 可以進行消費者的相關配置
        // 本地debug不提交offset consumer.setCommitOffsetsOnCheckpoints(false);
        return consumer;
    }
}

env.addSource(KafkaUtil.text("topic"));

2.搜索詞統計

在進行窗口內統計時,首先需要根據yyyy-MM-dd的維度對搜索詞消息進行keyby操作,形成KeyedStream,進一步調用實現了抽象類KeyedProcessFunction的方法。

2.1 KeyedProcessFunction介紹

顧名思義,KeyedProcessFunction,是針對具有相同key的stream進行元素處理的方法。
public abstract class KeyedProcessFunction<K, I, O> extends AbstractRichFunction
三個泛型分別是key的類型,流輸入類型,流輸出類型。

<1> 方法public abstract void processElement(I value, Context ctx, Collector<O> out) throws Exception;
處理流中的每一個元素,即每有一個元素進來,就會執行一次processElement方法。
該方法可以通過參數Collector<O> out來產生0個或者多個元素;
也可以通過Context ctx來更新state或者設置定時器timers。
ctx通過調用timerService()可以注冊定時器。

Context的屬性方法:

public abstract class Context {

        /**
         * Timestamp of the element currently being processed or timestamp of a firing timer.
         *
         * <p>This might be {@code null}, for example if the time characteristic of your program
         * is set to {@link org.apache.flink.streaming.api.TimeCharacteristic#ProcessingTime}.
         */
        public abstract Long timestamp();

        /**
         * A {@link TimerService} for querying time and registering timers.
         */
        public abstract TimerService timerService();

        /**
         * Emits a record to the side output identified by the {@link OutputTag}.
         *
         * @param outputTag the {@code OutputTag} that identifies the side output to emit to.
         * @param value The record to emit.
         */
        public abstract <X> void output(OutputTag<X> outputTag, X value);

        /**
         * Get key of the element being processed.
         */
        public abstract K getCurrentKey();
    }

對于timestamp()方法,需要注意的是注釋上說明可能會返回為null,如果設置的時間類型是ProcessingTime。

<2>方法public void onTimer(long timestamp, OnTimerContext ctx, Collector<O> out) throws Exception {}
當通過某個定時器timer通過TimerService設置后,會調用onTimer方法。

2.2 具體實現

因為需要實時統計當天的搜索詞熱度,所以在KeyedProcessFunction實現方法中,需要使用到狀態。
private MapState<String, DashboardKeyword> keywordState;
Map的鍵就是搜索詞,值就是輸出實體類(兩個屬性分別是關鍵詞和搜索次數)

@Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        StateTtlConfig retainOneDay = StateTtlUtil.retainOneDay();
        MapStateDescriptor<String, DashboardKeyword> keywordStateDescriptor = new MapStateDescriptor<>(
                "keyword",
                Types.STRING,
                Types.POJO(DashboardKeyword.class)
        );
        keywordStateDescriptor.enableTimeToLive(retainOneDay);

        this.keywordState = getRuntimeContext().getMapState(keywordStateDescriptor);
    }

KeyedProcessFunction繼承了AbstractRichFunction,因此可以使用到RuntimeContext。也進一步可以使用到狀態,在open方法里面定義State并且設置State的存活時間為1天。


@Override
    public void processElement(Search search, Context context, Collector<Tuple2<Integer, DashboardKeyword>> collector) throws Exception {
        Result result = DicAnalysis.parse(search.getKeyword());
        for (Term term: result.getTerms()) {
            String key = term.getName();
            if (key.trim().length() < 2) continue;

            DashboardKeyword value;
            if (this.keywordState.get(key) != null) {
                value = this.keywordState.get(key);
            } else {
                value = new DashboardKeyword();
                value.setKeyword(key);
                value.setFrequency(0L);
            }
            value.setFrequency(value.getFrequency() + 1L);
            this.keywordState.put(key, value);
        }

        long coalescedTime = ((System.currentTimeMillis() + 5000) / 5000) * 5000;
        context.timerService().registerProcessingTimeTimer(coalescedTime);
    }

processElement里面的代碼就是很常見的套路,如果MapState中已經存在當前搜索詞了,即獲取對應的value,并將其頻次增加;如果MapState中并沒有當前的搜索詞,則將該關鍵詞及對應value添加到Map當中。
這里是給定時器添加5s的時長,這里的寫法((System.currentTimeMillis() + 5000) / 5000) * 5000是計時器合并的目的,Flink對于每個鍵和時間戳都只會維護一個計時器(計時器太多會影響性能),需要通過降低計時器的精度來合并計時器,從而減少計時器的數量。
假設現在是15s,那么定時器為20s,利用上面的寫法,16s,17s,18s,19s的定時器都是20s。


 @Override
    public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<Integer, DashboardKeyword>> collector) throws Exception {
        java.util.stream.Collector<DashboardKeyword, ?, List<DashboardKeyword>> top50Collector = Comparators.greatest(
                50,
                Comparator.comparingLong(DashboardKeyword::getFrequency)
        );
        List<DashboardKeyword> top50 = Streams.stream(this.keywordState.values()).collect(top50Collector);

        for (int rank = 0; rank < top50.size(); rank++) {
            collector.collect(Tuple2.of(rank, top50.get(rank)));
        }
    }

統計前50搜索詞。

3.數據存儲

存儲到redis中,
注意flink1.7版本之后,官方沒有redis sink,可以去http://bahir.apache.org/(flink以及spark擴展庫),
粘貼源碼實現redis sink。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372

推薦閱讀更多精彩內容