一 项目依赖
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-scala_2.11</artifactId>
<version>1.7.2</version>
</dependency>
<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>
二 编码
2.1 批处理
从文件读取数据,对数据进行切分求wordcount
package com.gc.wc
import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.api.scala._
object BatchWordCount {
def main(args: Array[String]): Unit = {
val tool: ParameterTool = ParameterTool.fromArgs(args)
// 批处理执行环境
val env: ExecutionEnvironment = ExecutionEnvironment.getExecutionEnvironment
// dataSet 批处理
val dataSet: DataSet[String] = env.readTextFile(tool.get("path"))
var res: AggregateDataSet[(String, Int)] =dataSet.filter(_.nonEmpty)
.flatMap(_.split("\\W+"))
.map((_,1))
.groupBy(0)
.sum(1)
res.print()
}
}
2.2 流式WordCount
从scoket流中持续获取数据,对数据进行累加计算
package com.gc.wc
import org.apache.flink.api.java.utils.ParameterTool
import org.apache.flink.streaming.api.scala._
/**
* flink 流式处理
*/
object StreamWordCount {
def main(args: Array[String]): Unit = {
val params: ParameterTool = ParameterTool.fromArgs(args)
val host: String = params.get("host")
val port: Int = params.getInt("port")
// 流处理执行环境StreamExecutionEnvironment
val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment
// DataStream
val dataStream: DataStream[String] = env.socketTextStream(host,port)
val res: DataStream[(String, Int)] =dataStream.filter(_.nonEmpty)
.flatMap(_.split("\\W+"))
.map((_,1))
.keyBy(0)
.sum(1)
res.print() //打印
env.execute("StreamWordCount") // 执行
}
}