Flink中數(shù)量窗口增加等待時(shí)間

Flink窗口可以分為時(shí)間維度窗口和數(shù)據(jù)量窗口猜年。其中時(shí)間維度窗口又可分為ProcessingTime和EventTime适肠。一般情況下以時(shí)間作為窗口的應(yīng)用場景更多一些刁笙,比如:統(tǒng)計(jì)每分鐘的數(shù)據(jù)量、處理數(shù)據(jù)亂序等拧揽。

最近有這么一個場景慰照。采集kafka中數(shù)據(jù)并組裝成SQL批量寫入MySQL灶挟。由于MySQL對單個請求包(max_allowed_packet)有限制,所以考慮通過數(shù)量窗口來控制單個insert 語句的長度毒租。實(shí)踐過程中發(fā)現(xiàn)另外一個問題:如果窗口數(shù)量達(dá)不到稚铣,則一直不會觸發(fā),將導(dǎo)致數(shù)據(jù)入庫延遲

下面是實(shí)現(xiàn)數(shù)量窗口的代碼榛泛,類名稱:org.apache.flink.streaming.api.datastream.KeyedStream:

    /**
     * Windows this {@code KeyedStream} into tumbling count windows.
     *
     * @param size The size of the windows in number of elements.
     */
    public WindowedStream<T, KEY, GlobalWindow> countWindow(long size) {
        return window(GlobalWindows.create()).trigger(PurgingTrigger.of(CountTrigger.of(size)));
    }

創(chuàng)建一個全局window蝌蹂,緩存數(shù)據(jù)。后面通過觸發(fā)器觸發(fā)事件曹锨,后續(xù)由窗口處理函數(shù)對此窗口中的數(shù)據(jù)進(jìn)行處理孤个。那么CountTrigger中又是如何實(shí)現(xiàn)最大值呢?下面是CountTrigger的代碼:

/**
 * A {@link Trigger} that fires once the count of elements in a pane reaches the given count.
 *
 * @param <W> The type of {@link Window Windows} on which this trigger can operate.
 */
@PublicEvolving
public class CountTrigger<W extends Window> extends Trigger<Object, W> {
    private static final long serialVersionUID = 1L;

    private final long maxCount;

    private final ReducingStateDescriptor<Long> stateDesc =
            new ReducingStateDescriptor<>("count", new Sum(), LongSerializer.INSTANCE);

    private CountTrigger(long maxCount) {
        this.maxCount = maxCount;
    }

    @Override
    public TriggerResult onElement(Object element, long timestamp, W window, TriggerContext ctx) throws Exception {
        ReducingState<Long> count = ctx.getPartitionedState(stateDesc);
        count.add(1L);
        if (count.get() >= maxCount) {
            count.clear();
            return TriggerResult.FIRE;
        }
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onEventTime(long time, W window, TriggerContext ctx) {
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onProcessingTime(long time, W window, TriggerContext ctx) throws Exception {
        return TriggerResult.CONTINUE;
    }

    @Override
    public void clear(W window, TriggerContext ctx) throws Exception {
        ctx.getPartitionedState(stateDesc).clear();
    }

    @Override
    public boolean canMerge() {
        return true;
    }

    @Override
    public void onMerge(W window, OnMergeContext ctx) throws Exception {
        ctx.mergePartitionedState(stateDesc);
    }

    @Override
    public String toString() {
        return "CountTrigger(" +  maxCount + ")";
    }

    /**
     * Creates a trigger that fires once the number of elements in a pane reaches the given count.
     *
     * @param maxCount The count of elements at which to fire.
     * @param <W> The type of {@link Window Windows} on which this trigger can operate.
     */
    public static <W extends Window> CountTrigger<W> of(long maxCount) {
        return new CountTrigger<>(maxCount);
    }

    private static class Sum implements ReduceFunction<Long> {
        private static final long serialVersionUID = 1L;

        @Override
        public Long reduce(Long value1, Long value2) throws Exception {
            return value1 + value2;
        }

    }
}

onElement方法沛简,每次一個數(shù)據(jù)過來都會調(diào)用這個方法齐鲤。此類中實(shí)現(xiàn)了一個ReducingState,用來累加數(shù)據(jù)流入的數(shù)量椒楣,當(dāng)累加達(dá)到最大數(shù)量時(shí)给郊,會清除累加值,并觸發(fā)窗口函數(shù)進(jìn)行處理捧灰。TriggerResult.FIRE即是觸發(fā)執(zhí)行淆九。下面貼上TriggerResult的定義部分:

/**
     * No action is taken on the window.
     */
    CONTINUE,

    /**
     * {@code FIRE_AND_PURGE} evaluates the window function and emits the window
     * result.
     */
    FIRE_AND_PURGE,

    /**
     * On {@code FIRE}, the window is evaluated and results are emitted.
     * The window is not purged, though, all elements are retained.
     */
    FIRE,

    /**
     * All elements in the window are cleared and the window is discarded,
     * without evaluating the window function or emitting any elements.
     */
    PURGE;

CONTINUE:不做任何操作;
FIRE_AND_PURGE:觸發(fā)窗口事件并且清除窗口中積累的數(shù)據(jù)毛俏;
FIRE:觸發(fā)窗口事件不清除窗口中的累積的數(shù)據(jù)炭庙;
PURGE:只清除窗口中的數(shù)據(jù),且拋棄窗口煌寇;


如果需要CountTrigger響應(yīng)最大等待時(shí)間焕蹄,需要更改現(xiàn)有的onProcessingTime方法實(shí)現(xiàn),改成FIRE阀溶。為什么不直接改成FIRE_AND_PURGE呢腻脏,參考源代碼風(fēng)格,如果需要FIRE_AND_PURGE則外層使用PurgingTrigger.of進(jìn)行包裝银锻,這樣比較靈活永品。
新建Trigger類,的代碼如下:

/**
 * 可以指定最大窗口數(shù)量和等待的時(shí)間
 *
 * @param <W>
 * @author mingbozhang
 */
public class CountWithMaxTimeTrigger<W extends Window> extends Trigger<Object, W> {
    private static final long serialVersionUID = 1L;

    private final long maxCount;

    private final long maxWaitingTime;

    private final ReducingStateDescriptor<Long> stateDesc =
            new ReducingStateDescriptor<>("count", new CountWithMaxTimeTrigger.Sum(), LongSerializer.INSTANCE);
    /**
     * When merging we take the lowest of all fire timestamps as the new fire timestamp.
     */
    private final ReducingStateDescriptor<Long> fireTimeStateDesc =
            new ReducingStateDescriptor<>("fire-time", new CountWithMaxTimeTrigger.Min(), LongSerializer.INSTANCE);

    private CountWithMaxTimeTrigger(long maxCount, long maxWaitingTime) {
        this.maxCount = maxCount;
        this.maxWaitingTime = maxWaitingTime;
    }

    /**
     * Creates a trigger that fires once the number of elements in a pane reaches the given count.
     *
     * @param maxCount       The count of elements at which to fire.
     * @param maxWaitingTime max waiting ms
     * @param <W>            The type of {@link Window Windows} on which this trigger can operate.
     */
    public static <W extends Window> CountWithMaxTimeTrigger<W> of(long maxCount, long maxWaitingTime) {
        return new CountWithMaxTimeTrigger<>(maxCount, maxWaitingTime);
    }

    @Override
    public TriggerResult onElement(Object element, long timestamp, W window, TriggerContext ctx) throws Exception {
        ReducingState<Long> count = ctx.getPartitionedState(stateDesc);
        ReducingState<Long> fireTimestamp = ctx.getPartitionedState(fireTimeStateDesc);

        count.add(1L);
        if (count.get() >= maxCount) {
            count.clear();
            fireTimestamp.clear();
            return TriggerResult.FIRE;
        }

        if (fireTimestamp.get() == null) {
            long triggerTime = System.currentTimeMillis() + maxWaitingTime;
            ctx.registerProcessingTimeTimer(triggerTime);
            fireTimestamp.add(triggerTime);
        }

        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onEventTime(long time, W window, TriggerContext ctx) {
        return TriggerResult.CONTINUE;
    }

    @Override
    public TriggerResult onProcessingTime(long time, W window, TriggerContext ctx) throws Exception {
        ReducingState<Long> fireTimestamp = ctx.getPartitionedState(fireTimeStateDesc);

        if (fireTimestamp.get() != null && fireTimestamp.get().equals(time)) {
            ctx.getPartitionedState(stateDesc).clear();
            fireTimestamp.clear();
            return TriggerResult.FIRE;
        }

        return TriggerResult.CONTINUE;
    }

    @Override
    public void clear(W window, TriggerContext ctx) throws Exception {
        ctx.getPartitionedState(stateDesc).clear();
    }

    @Override
    public boolean canMerge() {
        return true;
    }

    @Override
    public void onMerge(W window, OnMergeContext ctx) throws Exception {
        ctx.mergePartitionedState(stateDesc);
    }

    @Override
    public String toString() {
        return "CountTrigger(" + maxCount + ")";
    }

    private static class Sum implements ReduceFunction<Long> {
        private static final long serialVersionUID = 1L;

        @Override
        public Long reduce(Long value1, Long value2) throws Exception {
            return value1 + value2;
        }

    }

    private static class Min implements ReduceFunction<Long> {
        private static final long serialVersionUID = 1L;

        @Override
        public Long reduce(Long value1, Long value2) throws Exception {
            return Math.min(value1, value2);
        }
    }
}

在onElement中注冊Timer:

 if (fireTimestamp.get() == null) {
            long triggerTime = System.currentTimeMillis() + maxWaitingTime;
            ctx.registerProcessingTimeTimer(triggerTime);
            fireTimestamp.add(triggerTime);
  }

在onProcessingTime中觸發(fā)窗口事件徒仓,并且清除最大數(shù)據(jù)量計(jì)數(shù)器:

@Override
    public TriggerResult onProcessingTime(long time, W window, TriggerContext ctx) throws Exception {
        ReducingState<Long> fireTimestamp = ctx.getPartitionedState(fireTimeStateDesc);

        if (fireTimestamp.get() != null && fireTimestamp.get().equals(time)) {
            ctx.getPartitionedState(stateDesc).clear();
            fireTimestamp.clear();
            return TriggerResult.FIRE;
        }

        return TriggerResult.CONTINUE;
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末腐碱,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子掉弛,更是在濱河造成了極大的恐慌,老刑警劉巖喂走,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件殃饿,死亡現(xiàn)場離奇詭異,居然都是意外死亡芋肠,警方通過查閱死者的電腦和手機(jī)乎芳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人奈惑,你說我怎么就攤上這事吭净。” “怎么了肴甸?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵寂殉,是天一觀的道長。 經(jīng)常有香客問我原在,道長友扰,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任庶柿,我火速辦了婚禮村怪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘浮庐。我一直安慰自己甚负,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布审残。 她就那樣靜靜地躺著梭域,像睡著了一般。 火紅的嫁衣襯著肌膚如雪维苔。 梳的紋絲不亂的頭發(fā)上碰辅,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天,我揣著相機(jī)與錄音介时,去河邊找鬼没宾。 笑死,一個胖子當(dāng)著我的面吹牛沸柔,可吹牛的內(nèi)容都是我干的循衰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼褐澎,長吁一口氣:“原來是場噩夢啊……” “哼会钝!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起工三,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤迁酸,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后俭正,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體奸鬓,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年掸读,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了串远。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片宏多。...
    茶點(diǎn)故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖澡罚,靈堂內(nèi)的尸體忽然破棺而出伸但,到底是詐尸還是另有隱情,我是刑警寧澤留搔,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布更胖,位于F島的核電站,受9級特大地震影響催式,放射性物質(zhì)發(fā)生泄漏函喉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一荣月、第九天 我趴在偏房一處隱蔽的房頂上張望管呵。 院中可真熱鬧,春花似錦哺窄、人聲如沸捐下。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽坷襟。三九已至,卻和暖如春生年,著一層夾襖步出監(jiān)牢的瞬間婴程,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工抱婉, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留档叔,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓蒸绩,卻偏偏與公主長得像衙四,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子患亿,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容