




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 天然气的生产工艺与装备改造考核试卷
- 报纸的数码产品考核试卷
- 海上油气平台设计的抗地震性能优化考核试卷
- 未来的太空旅游与星际旅行体验考核试卷
- 残疾人就业创业支持考核试卷
- 煤炭批发业务流程重组与效能提升考核试卷
- 体育赛事技术创新与设备应用考核试卷
- 油气储存设施设计与布局考核试卷
- 小吃店品牌形象更新与市场反馈考核试卷
- 洗浴环境氛围营造考核试卷
- XXX医院CT检查报告单模板可编辑范本
- DB3502-T 141-2024 城市道路开口设置指引
- 分泌性中耳炎-3
- 工厂车间生产工艺培训
- 《中国心力衰竭诊断和治疗指南2024》解读(下)
- DB4202T 39-2024 城市桥梁与隧道运行监测技术规范
- 器官捐献合作协议书范文模板
- GB/T 6556-2024机械密封的型式、主要尺寸、材料和识别标志
- 新人教版英语五年级下册教材解读
- 异常子宫出血护理
- 《马克思主义发展史》题集
评论
0/150
提交评论