flink window实例分析
window是处理数据的核心。按需选择你需要的窗口类型后,它会将传入的原始数据流切分成多个buckets,所有计算都在window中进行。
flink本身提供的实例程序TopSpeedWindowing.java
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.java.tuple.Tuple4;
import org.apache.flink.api.java.utils.ParameterTool;
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.source.SourceFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.streaming.api.functions.windowing.delta.DeltaFunction;
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows;
import org.apache.flink.streaming.api.windowing.evictors.TimeEvictor;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.triggers.DeltaTrigger; import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.TimeUnit; /**
* An example of grouped stream windowing where different eviction and trigger
* policies can be used. A source fetches events from cars every 100 msec
* containing their id, their current speed (kmh), overall elapsed distance (m)
* and a timestamp. The streaming example triggers the top speed of each car
* every x meters elapsed for the last y seconds.
*/
public class TopSpeedWindowing { // *************************************************************************
// PROGRAM
// ************************************************************************* public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
env.getConfig().setGlobalJobParameters(params); @SuppressWarnings({"rawtypes", "serial"})
DataStream<Tuple4<Integer, Integer, Double, Long>> carData;
if (params.has("input")) {
carData = env.readTextFile(params.get("input")).map(new ParseCarData());
} else {
System.out.println("Executing TopSpeedWindowing example with default input data set.");
System.out.println("Use --input to specify file input.");
carData = env.addSource(CarSource.create(2));
} int evictionSec = 10;
double triggerMeters = 50;
DataStream<Tuple4<Integer, Integer, Double, Long>> topSpeeds = carData
.assignTimestampsAndWatermarks(new CarTimestamp()) //1
.keyBy(0)
.window(GlobalWindows.create()) //2
.evictor(TimeEvictor.of(Time.of(evictionSec, TimeUnit.SECONDS))) //3
.trigger(DeltaTrigger.of(triggerMeters,
new DeltaFunction<Tuple4<Integer, Integer, Double, Long>>() {//4
private static final long serialVersionUID = 1L; @Override
public double getDelta(
Tuple4<Integer, Integer, Double, Long> oldDataPoint,
Tuple4<Integer, Integer, Double, Long> newDataPoint) {
return newDataPoint.f2 - oldDataPoint.f2;
}
}, carData.getType().createSerializer(env.getConfig())))//4
.maxBy(1); if (params.has("output")) {
topSpeeds.writeAsText(params.get("output"));
} else {
System.out.println("Printing result to stdout. Use --output to specify output path.");
topSpeeds.print();
} env.execute("CarTopSpeedWindowingExample");
} // *************************************************************************
// USER FUNCTIONS
// ************************************************************************* private static class CarSource implements SourceFunction<Tuple4<Integer, Integer, Double, Long>> { private static final long serialVersionUID = 1L;
private Integer[] speeds;
private Double[] distances; private Random rand = new Random(); private volatile boolean isRunning = true; private CarSource(int numOfCars) {
speeds = new Integer[numOfCars];
distances = new Double[numOfCars];
Arrays.fill(speeds, 50);
Arrays.fill(distances, 0d);
} public static CarSource create(int cars) {
return new CarSource(cars);
} @Override
public void run(SourceContext<Tuple4<Integer, Integer, Double, Long>> ctx) throws Exception { while (isRunning) {
Thread.sleep(100);
for (int carId = 0; carId < speeds.length; carId++) {
if (rand.nextBoolean()) {
speeds[carId] = Math.min(100, speeds[carId] + 5);
} else {
speeds[carId] = Math.max(0, speeds[carId] - 5);
}
distances[carId] += speeds[carId] / 3.6d;
Tuple4<Integer, Integer, Double, Long> record = new Tuple4<>(carId,
speeds[carId], distances[carId], System.currentTimeMillis());
ctx.collect(record);
}
}
} @Override
public void cancel() {
isRunning = false;
}
} private static class ParseCarData extends RichMapFunction<String, Tuple4<Integer, Integer, Double, Long>> {
private static final long serialVersionUID = 1L; @Override
public Tuple4<Integer, Integer, Double, Long> map(String record) {
String rawData = record.substring(1, record.length() - 1);
String[] data = rawData.split(",");
return new Tuple4<>(Integer.valueOf(data[0]), Integer.valueOf(data[1]), Double.valueOf(data[2]), Long.valueOf(data[3]));
}
} private static class CarTimestamp extends AscendingTimestampExtractor<Tuple4<Integer, Integer, Double, Long>> {
private static final long serialVersionUID = 1L; @Override
public long extractAscendingTimestamp(Tuple4<Integer, Integer, Double, Long> element) {
return element.f3;
}
} }
其中,
1. 定义时间戳,上篇文章<flink中的时间戳如何使用?---Watermark使用及原理>上进行了介绍,本篇不做赘述。
2.窗口类型,Windows Assigner定义如何将数据流分配到一个或者多个窗口;其层次结构如下:

evictor:用于数据剔除,其层次结构如下:

3. trigger:窗口触发器,其层次结构如下:

4. Window function定义窗口内数据的计算逻辑,其层次结构如下:

参考资料
【1】https://www.jianshu.com/p/5302b48ca19b
flink window实例分析的更多相关文章
- Camera图像处理原理及实例分析-重要图像概念
Camera图像处理原理及实例分析 作者:刘旭晖 colorant@163.com 转载请注明出处 BLOG:http://blog.csdn.net/colorant/ 主页:http://rg ...
- 一些有用的javascript实例分析(三)
原文:一些有用的javascript实例分析(三) 10 输入两个数字,比较大小 window.onload = function () { var aInput = document.getElem ...
- 一些有用的javascript实例分析(一)
原文:一些有用的javascript实例分析(一) 本文以http://fgm.cc/learn/链接的实例索引为基础,可参见其实际效果.分析和整理了一些有用的javascript实例,相信对一些初学 ...
- 一些有用的javascript实例分析(二)
原文:一些有用的javascript实例分析(二) 5 求出数组中所有数字的和 window.onload = function () { var oBtn = document.getElement ...
- Camera图像处理原理及实例分析
Camera图像处理原理及实例分析 作者:刘旭晖 colorant@163.com 转载请注明出处 BLOG:http://blog.csdn.net/colorant/ 主页:http://rg ...
- Watchdog问题实例分析
1.日志获取 Watchdog相关的问题甚至需要以下所有的日志: logcat 通过adb logcat命令输出Android的一些当前运行日志,可以通过logcat的 -b 参数指定要输出的日志缓冲 ...
- RPC原理及RPC实例分析
在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...
- java基础学习05(面向对象基础01--类实例分析)
面向对象基础01(类实例分析) 实现的目标 1.如何分析一个类(类的基本分析思路) 分析的思路 1.根据要求写出类所包含的属性2.所有的属性都必须进行封装(private)3.封装之后的属性通过set ...
- (转)实例分析:MySQL优化经验
[IT专家网独家]同时在线访问量继续增大,对于1G内存的服务器明显感觉到吃力,严重时甚至每天都会死机,或者时不时的服务器卡一下,这个问题曾经困扰了我半个多月.MySQL使用是很具伸缩性的算法,因此你通 ...
随机推荐
- Apache Cordova for ios环境配置
原文:Apache Cordova for ios环境配置 1.安装针对iOS的工具 https://technet.microsoft.com/ZH-cn/library/dn757054.aspx ...
- BGP的一网双平面规划
网络拓扑: XRV1 ===================================================================== # sysname XRV1# boa ...
- 正试图在 os 加载程序锁内执行托管代码
正试图在 os 加载程序锁内执行托管代码.不要尝试在 DllMain 或映像初始化函数内运行托管代码... 当我在窗体初始化的时候,调用了一个外部的dill时,它就不知什么原因的 抛出一个“正试图在 ...
- Java8 的一些新特性总结
目前Java8已经发布很多个版本了,对于Java8中的新特性虽然有各位大神进行jdk8的英文特性文档翻译,但都太官方化语言,对照几篇翻译本人对新特性文档做一下总结,以帮助我和各位不了解Java8新特性 ...
- Linux文件系统操作与磁盘管理
简单文件操作 df---->report file system disk space usage du---->estimate file space usage 2.简单的磁盘管理 d ...
- Android源码中编译出指定jar包
今天想把android源码/vendor/letv/frameworks/base/java下的源码编译成 framework-letv.jar供乐乐语音客户端使用,编译完后,发现jar包文件虽然生成 ...
- Qt中连接到同一signal的多个slots的执行顺序问题(现在是看连接顺序,以前是无序的)
in the order they have been connected 起源 前些天忘记在哪儿讨论过这个问题,今天在csdn又看到有网友问这个问题,而其他网友却无一例外的给出了“无序”这个答案. ...
- Delphi指针运用理解
现在是面向对象漫天飞的年代了,大家都在在谈面向对象编程.Java对指针“避而不谈”,C#虽然支持指针运用,但是也淡化处理. 然而,指针还是好完全掌握为妙,省得在开发过程碰钉子,至于对指针的运用在于开发 ...
- NSTimer 的简易使用方法
一.使用方式 1.声明NSTimer方法 static CGFloat sIntervalTime = 15.f; //定时刷新时间间隔 @property (nonatomic, stron ...
- l论文查重平台
推荐大家一个靠谱的论文检测平台.重复的部分有详细出处以及具体修改意见,能直接在文章上做修改,全部改完一键下载就搞定了.怕麻烦的话,还能用它自带的降重功能.哦对了,他们现在正在做毕业季活动, 赠送很多免 ...