版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、Apache Flink TrainingDataStream API BasicDecember 10, 2015DataStream APIStream ProcessingJava and ScalaAll examples here in Java for Flink 0.10Documentation available at 2DataStream API by Example3Window WordCount: main Method4public static void main(String args) throws Exception / set up the execut
2、ion environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / spl
3、it up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0” .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCoun
4、t Example);Stream Execution Environment5public static void main(String args) throws Exception / set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.Even
5、tTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0” .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tu
6、ple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCount Example);Data Sources6public static void main(String args) throws Exception / set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecu
7、tionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the
8、 tuple field 0 .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCount Example);Data types7public static void main(String args) throws Exception / set up the ex
9、ecution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) /
10、 split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0 .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordC
11、ount Example);Transformations8public static void main(String args) throws Exception / set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); Da
12、taStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0 .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1
13、 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCount Example);User functions9public static void main(String args) throws Exception / set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvir
14、onment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple fi
15、eld 0” .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCount Example);DataSinks10public static void main(String args) throws Exception / set up the execution
16、environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split u
17、p the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0” .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); / print result in command line counts.print(); / execute program env.execute(Socket WordCount Ex
18、ample);Execute!11public static void main(String args) throws Exception / set up the execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); / configure event time env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime); DataStreamTuple
19、2 counts = env / read stream of words from socket .socketTextStream(localhost, 9999) / split up the lines in tuples containing: (word,1) .flatMap(new Splitter() / key stream by the tuple field 0” .keyBy(0) / compute counts every 5 minutes .timeWindow(Time.minutes(5) /sum up tuple field 1 .sum(1); /
20、print result in command line counts.print(); / execute program env.execute(Socket WordCount Example);Window WordCount: FlatMappublic static class Splitter implements FlatMapFunctionString, Tuple2 Override public void flatMap(String value, CollectorTuple2 out) throws Exception / normalize and split t
21、he line String tokens = value.toLowerCase().split(W+); / emit the pairs for (String token : tokens) if (token.length() 0) out.collect( new Tuple2(token, 1); 12WordCount: Map: Interface13public static class Splitter implements FlatMapFunctionString, Tuple2 Override public void flatMap(String value, C
22、ollectorTuple2 out) throws Exception / normalize and split the line String tokens = value.toLowerCase().split(W+); / emit the pairs for (String token : tokens) if (token.length() 0) out.collect( new Tuple2(token, 1); WordCount: Map: Types14public static class Splitter implements FlatMapFunctionStrin
23、g, Tuple2 Override public void flatMap(String value, CollectorTuple2 out) throws Exception / normalize and split the line String tokens = value.toLowerCase().split(W+); / emit the pairs for (String token : tokens) if (token.length() 0) out.collect( new Tuple2(token, 1); WordCount: Map: Collector15pu
24、blic static class Splitter implements FlatMapFunctionString, Tuple2 Override public void flatMap(String value, CollectorTuple2 out) throws Exception / normalize and split the line String tokens = value.toLowerCase().split(W+); / emit the pairs for (String token : tokens) if (token.length() 0) out.co
25、llect( new Tuple2(token, 1); DataStream API Concepts16(Selected) Data TypesBasic Java TypesString, Long, Integer, Boolean,ArraysComposite TypesTuplesMany more (covered in the advanced slides)17TuplesThe easiest and most lightweight way of encapsulating data in FlinkTuple1 up to Tuple25Tuple2 person
26、= new Tuple2(Max, Mustermann”);Tuple3 person = new Tuple3(Max, Mustermann, 42);Tuple4 person = new Tuple4(Max, Mustermann, 42, true);/ zero based index!String firstName = person.f0;String secondName = person.f1;Integer age = person.f2;Boolean fired = person.f3;18Transformations: MapDataStream intege
27、rs = env.fromElements(1, 2, 3, 4);/ Regular Map - Takes one element and produces one elementDataStream doubleIntegers = integers.map(new MapFunction() Override public Integer map(Integer value) return value * 2; );doubleIntegers.print(); 2, 4, 6, 8/ Flat Map - Takes one element and produces zero, on
28、e, or more elements.DataStream doubleIntegers2 = integers.flatMap(new FlatMapFunction() Override public void flatMap(Integer value, Collector out) out.collect(value * 2); );doubleIntegers2.print(); 2, 4, 6, 819Transformations: Filter/ The DataStreamDataStream integers = env.fromElements(1, 2, 3, 4);
29、DataStream filtered = integers.filter(new FilterFunction() Override public boolean filter(Integer value) return value != 3; );filtered.print(); 1, 2, 420Transformations: KeyByA DataStream can be organized by a keyPartitions the data (all elements with the same key are processed by the same operator)
30、Certain operators are key-awareOperator state can be partitioned by key21/ (name, age) of employeesDataStreamTuple2 passengers = / group by second field (age)DataStream grouped = passengers.keyBy(1)Stephan, 18Fabian, 23Julia, 27Anna, 18Romeo, 27Anna, 18Stephan, 18Julia, 27Romeo, 27Fabian, 23Ben, 25B
31、en, 25Data Shipping StrategiesOptionally, you can specify how data is shipped between two transformationsForward: stream.forward()Only local communicationRebalance: stream.rebalance()Round-robin partitioningPartition by hash: stream.partitionByHash(.)Custom partitioning: stream.partitionCustom(.)Bro
32、adcast: stream.broadcast()Broadcast to all nodes22Rich Functions23RichFunctionsFunction interfaces have only one methodSingle abstract method (SAM)Support for Java8 Lambda functionsThere is a “Rich” variant for each function.RichFlatMapFunction, Additional methodsopen(Configuration c)close()getRunti
33、meContext()24RichFunctions & RuntimeContextRuntimeContext has useful methods:getIndexOfThisSubtask ()getNumberOfParallelSubtasks()getExecutionConfig() Hands out partitioned state (later discussed)getKeyValueState() 25Data Sources26Data Sources: CollectionsStreamExecutionEnvironment env = StreamExecu
34、tionEnvironment.getExecutionEnvironment();/ read from elementsDataStream names = env.fromElements(“Some”, “Example”, “Strings”);/ read from Java collectionList list = new ArrayList(); list.add(“Some”); list.add(“Example”); list.add(“Strings”);DataStream names = env.fromCollection(list);27Data Source
35、s: Files & SocketsStreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();/ read text socket from portDataStream socketLines = env.socketTextStream(localhost, 9999);/ read a text file ingesting new elements every 100 millisecondsDataStream localLines = env.readFileStrea
36、m(/path/to/file, 100, WatchType.PROCESS_ONLY_APPENDED);28Custom SourceFunctions & ConnectorsStreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();/ read data stream from custom source functionDataStreamTuple2 stream = env.addSource(new MySourceFunction();Flink has con
37、nectors for many stream serving systemsApache KafkaRabbitMQ29Data Sinks30Data SinksWrite as text file using toString()stream.writeAsText(“/path/to/file”)Write as CSV filestream.writeAsCsv(“/path/to/file”)Print to the standard outputstream.print()Emit to socketstream .writeToSocket(host,port,Serializ
38、ationSchema)31Custom Sinks & ConnectorsEmit data with a custom sink functionstream.addSink(new MySinkFunction();Several connectors Apache KafkaElasticsearchRolling Files (HDFS, S3, )32ExecutionPrograms are lazily executed when execute() is calledDataStream result;/ nothing happensresult.writeToSocke
39、t(.);/ nothing happensresult.writeAsText(/path/to/file, n, |);/ Execution really starts hereenv.execute();33Fault-Tolerance and Operator State34Fault Tolerance in FlinkFlink takes a checkpoint of an application every N milliseconds and rolls back to the checkpointed state in case of a failureEnable
40、exactly-once consistency (checkpoint every 5 seconds)env.enableCheckpointing(5000) Enable at-least-once consistency (for lower latency)env.enableCheckpointing(5000, CheckpointingMode.AT_LEAST_ONCE)Setting the interval to few seconds should be good for most applicationIf checkpointing is not enabled, no recovery guarantees are providedSee documentation for details: 35Stateful FunctionsAll DataStream functions can be statefulState is checkpointed and recovered in case of a failure (if checkpointing is enabled).You can define two types of stateLocal State: Functions can register local variabl
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2026年包头铁道职业技术学院单招职业技能笔试备考题库带答案解析
- 2026年桂林山水职业学院高职单招职业适应性测试参考题库有答案解析
- 2026年抚州职业技术学院单招职业技能笔试备考题库带答案解析
- 保安员上岗资格证考试试题题库与答案
- 2026年闽江学院高职单招职业适应性测试备考试题有答案解析
- 2026年荆门职业学院单招综合素质笔试模拟试题带答案解析
- 春游礼品活动策划方案(3篇)
- 咖啡换购活动策划方案(3篇)
- 双人烧烤活动方案策划(3篇)
- 考证讲座活动策划方案(3篇)
- 2026年日历表含农历(2026年12个月日历-每月一张A4可打印)
- 输变电工程多维立体参考价(2025年版)
- 平衡鸟课件教案
- 动脉瘤栓塞术后的护理
- 幼儿园安全管理制度汇编本
- 灵犬莱西考试题及答案
- 山东省泰安市泰山区2024-2025学年五年级上学期期末英语试题
- 挤塑机工操作规程(4篇)
- 陕西省咸阳市秦都区2024-2025学年七年级上学期1月期末考试语文试卷(无答案)
- AI虚拟数字人教学课件 第5章 腾讯智影:生成数字人视频与主播
- CJJT269-2017城市综合地下管线信息系统技术规范正式版
评论
0/150
提交评论