搭建 maven 工程 FlinkTutorial
然后在pom.xml中添加依赖,和引入插件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.slabout</groupId>
<artifactId>FlinkTutor</artifactId>
<version>1.0-SNAPSHOT</version>
<!--引入依赖文件-->
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-scala_2.11</artifactId>
<version>1.7.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.flink/flink-streaming-scala -->
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_2.11</artifactId>
<version>1.7.2</version>
</dependency>
</dependencies>
<!--引入需要的插件-->
<build>
<plugins>
<!-- 该插件用于将 Scala 代码编译成 class 文件 -->
<plugin>
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.4.6</version>
<executions>
<execution>
<!-- 声明绑定到 maven 的 compile 阶段 -->
<goals>
<goal>testCompile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
<executions>
<execution>
<id>make-assembly</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
引入框架支持
创建一个单例对象
批处理实现
package com.slabout.wc
import org.apache.flink.api.scala._
// 批处理word count 程序
object WordCount {
// 创建一个main方法
def main(args: Array[String]): Unit = {
// 1、创建一个执行环境
val env = ExecutionEnvironment.getExecutionEnvironment
// 2、从文件中读取数据
val inputPath = "D:\\IEDA\\FlinkTutor\\src\\main\\resources\\hello"
val inputDataSet = env.readTextFile(inputPath)
// 3、切分数据得到word,然后按word做分组聚合
// _此处代表的是word
val wordCountDataSet = inputDataSet.flatMap(_.split(" "))
.map((_,1)) // 来一个数据计数一次1
.groupBy(0) // 按照map中0位置的那个是:word,进行分组 (可看源码)
.sum(1) // 统计的是map中1位置的那个数值
// 4、打印结果
wordCountDataSet.print()
}
}
流处理实现
package com.slabout.wc
import org.apache.flink.streaming.api.scala._
// 流处理word count程序
object StreamWordCount {
def main(args: Array[String]): Unit = {
// 1、创建流处理执行环境
val env = StreamExecutionEnvironment.getExecutionEnvironment
// 2、接收一个socket文本流(因为要以流的形式获取数据处理)
// 绑定主机名和端口号
val dataStream = env.socketTextStream("localhost",7777)
// 3、对每条数据进行处理
val wordCountDataStream = dataStream.flatMap(_.split(" "))
.filter(_.nonEmpty)
.map((_,1)) // 转换为一个二元组去计数
.keyBy(0) // 用keyBy进行分组
.sum(1)
wordCountDataStream.print()
// 到上面为止是定义好程序的过程而已
// 启动executor
env.execute("Stream word count job")
// 然后就可以传入数据,看打印效果
// 可以设置并行度
// 并行度就是执行的线程的数量(开发环境的话默认的并行度是电脑的核数)
// wordCountDataStream.setParallelism(2)
}
}