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

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

流处理实现WordCount,从Socket中读取内容,作为输入源进行计算

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、开启socket服务
在linux服务器上执行命令:nc -lk 7777
用于后续测试数据输入

3、代码实现

package org.itzhimei;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

/**
 * 流处理实现WordCount
 */
public class WordCountStreamSocket {

    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
		//监听Socket端口,获取数据
        DataStream<String> dataStream = env.socketTextStream("localhost", 7777);

		//程序每读取一行数据,马上在之前的计算结果基础上,累计当前行的数据,进行计算并输出了结果
        //数据计算
        //通过自定义类MyBatchFlatMapper,实现分词
        //keyBy(item->item.f0)进行分组,取二元组第一个元素进行分组
        //通过sum(1)进行汇总,1标识二元组中的第二个值,也就是单词出现的次数1
        SingleOutputStreamOperator<Tuple2<String, Integer>> result = dataStream.flatMap(new MyStreamFlatMap())
                .keyBy(item->item.f0)
                .sum(1);
        result.print();
        env.execute();
    }

    private static class MyStreamFlatMap implements FlatMapFunction<String, Tuple2<String, Integer>> {
        @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));
            }
        }
    }
}

4、测试数据和输出结果
因为数据是实时统计的,每当我输入一行数据,程序马上在之前的计算结果基础上,累计当前行的数据,进行计算并输出结果。


输入:hello Flink
输出:
16> (Flink,1)
5> (hello,1)

输入:hello Java
输出:
13> (Java,1)
5> (hello,2)

输入:how are you
输出:
8> (are,1)
10> (you,1)
11> (how,1)

输入:I'm fine thank you and you
输出:
15> (and,1)
9> (fine,1)
6> (thank,1)
3> (I'm,1)
10> (you,2)
10> (you,3)

输入:I'm Ok
输出:
3> (I'm,2)
1> (Ok,1)

5、输出结果

16> (Flink,1)
5> (hello,1)
13> (Java,1)
5> (hello,2)
8> (are,1)
10> (you,1)
11> (how,1)
15> (and,1)
9> (fine,1)
6> (thank,1)
3> (I'm,1)
10> (you,2)
10> (you,3)
3> (I'm,2)
1> (Ok,1)

6、API分析
基本流程是:
1)创建执行环境对象
2)获取数据源
3)计算
4)输出结果