前言
前一篇文章大概讲了下自定义Trigger窗口触发器,本文讲述下Evictor窗口数据驱逐器的使用。
Evictor
作用:用来剔除窗口中的数据。
举个例子: 去统计订单中每个窗口中订单金额大于4的订单。
这个正常情况下会用个filter或者flatmap算子去做过滤。为了演示效果也可以用evictor去实现~
evictor中有两个方法:
/**
* Optionally evicts elements. Called before windowing function.
*
* @param elements The elements currently in the pane.
* @param size The current number of elements in the pane.
* @param window The {@link Window}
* @param evictorContext The context for the Evictor
*/
// before是在窗口触发之前调用的,如果剔除是在before里那么后面的reduce和aggregate都会等数据到了后再执行
void evictBefore(Iterable<TimestampedValue<T>> elements, int size, W window, EvictorContext evictorContext);
/**
* Optionally evicts elements. Called after windowing function.
*
* @param elements The elements currently in the pane.
* @param size The current number of elements in the pane.
* @param window The {@link Window}
* @param evictorContext The context for the Evictor
*/
// after是在窗口触发后剔除数据
void evictAfter(Iterable<TimestampedValue<T>> elements, int size, W window, EvictorContext evictorContext);
测试代码如下:
定义Evictor 实现evictorBefore
package com.realtime.flink.evictor;
import com.realtime.flink.dto.OrderDto;
import org.apache.flink.streaming.api.windowing.evictors.Evictor;
import org.apache.flink.streaming.api.windowing.windows.Window;