Flink从入门到实战一[快速上手]-3-Flink HelloWorld之批处理WordCount

flink中的数据分为有界流数据和无界流数据,对应的处理计算叫做批处理和流处理,批处理对应的API是DataSet,流处理对应的API是DataStream。

Flink1.14.3简单demo

我们接下来以Flink1.14.3版本为例实现一个Flink简单demo,以批处理方式实现WordCount,从文件中读取内容,作为输入源进行计算

1、pom引入

<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-java</artifactId>
  <version>1.14.3</version>
</dependency>
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-streaming-java_2.11</artifactId>
  <version>1.14.3</version>
</dependency>
<dependency>
  <groupId>org.apache.flink</groupId>
  <artifactId>flink-clients_2.11</artifactId>
  <version>1.14.3</version>
</dependency>

2、代码实现

package org.itzhimei;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * 批处理实现WordCount
 *
 */
public class WordCountBatch {

    public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //获取数据源
        String input = "D:\\______flink______\\input\\wordcount.txt";
        DataSet<String> inputDataSet = env.readTextFile(input);

		//批处理:数据是一次性读取后,全部计算完,再输出
        //数据计算
        //通过自定义类MyBatchFlatMapper,实现分词
        //通过groupBy(0)进行分组,0标识二元组中的第一个值,也就是word,这里是按照每个单词进行分组
        //通过sum(1)进行汇总,1标识二元组中的第二个值,也就是单词出现的次数1
        DataSet<Tuple2<String, Integer>> result = inputDataSet.flatMap(new MyBatchFlatMapper())
                .groupBy(0)
                .sum(1);
        result.print();
        
    }

    private static class MyBatchFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        /**
         * collector返回创建的二元组对象,二元组对象每个单词作为一个结果,其值为1,为了后续分组统计做准备
         * @param s 输入
         * @param collector 结果输出对象
         * @throws Exception
         */
        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = s.split(" ");
            for(String word:words) {
                collector.collect(new Tuple2<>(word,1));
            }
        }
    }
}

3、测试数据
hello Flink
hello Java
how are you
I’m fine thank you and you
I’m Ok

4、输出结果

因为是批处理,数据是一次性读取后,全部计算完,再输出,结果如下:

(Ok,1)
(I'm,2)
(hello,2)
(and,1)
(Java,1)
(fine,1)
(how,1)
(you,3)
(are,1)
(thank,1)
(Flink,1)