Flink使用滚动窗进行JSON事件计数
目录
从Kafka接收Json事件进行反序列化,根据事件类型字符串进行5秒的滚动窗事件数目统计。
json事件反序列化请参见前面文章。
定义计数累积函数
定义AggregateFunction和WindowFunction
方法一 重载AggregateFunction的Add
public static class MyCountAggregate implements AggregateFunction<SecEvent, Long, Long> {
@Override
public Long createAccumulator() {
/*访问量初始化为0*/
return 0L;
}
@Override
public Long add(SecEvent value, Long accumulator) {
/*访问量直接+1 即可*/
return accumulator+1;
}
@Override
public Long getResult(Long accumulator) {
return accumulator;
}
/*合并两个统计量*/
@Override
public Long merge(Long a, Long b) {
return a+b;
}
}
public static class MyCountWindowFunction implements WindowFunction<Long,String,String, TimeWindow> {
@Override
public void apply(String eventType, TimeWindow window, Iterable<Long> input, Collector<String> out) throws Exception {
/* 输出 */
/*out.collect("productId"productId,window.getEnd(),input.iterator().next()));*/
out.collect("----------------窗口时间:"+window.getEnd());
out.collect("事件: " + eventType + " 数目: "+ input.iterator().next());
<