1.使用maven构建flink项目
本地需要java和scala,我已经装好了。
我的pom文件:
<?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>org.example</groupId>
<artifactId>flinktest</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-scala_2.12</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.flink</groupId>
<artifactId>flink-streaming-scala_2.12</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>
2.批处理:
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.api.scala._
object wc {
def main(args: Array[String]): Unit = {
val env = ExecutionEnvironment.getExecutionEnvironment
val inputPath="C:\\Users\\caoji\\IdeaProjects\\flinktest\\src\\main\\resources\\cj.text"
val inputDataSet=env.readTextFile(inputPath)
val result=inputDataSet.flatMap(_.split(" ")).map((_,1)).groupBy(0).sum(1)
result.print()
}
}
在cj.text中写一些内容,执行结果如下:
3.流处理
因为要使用linux的nc -lk,在windows环境下可以使用自带linux bash。我按照https://blog.csdn.net/rockyzhang1992/article/details/79648333这篇博客的方法进行操作。
步骤1:配置并启用自带linux虚拟机
步骤2:安装linux,我是在microsoft store下载的ubuntu
步骤3:在cmd输入bash就可以进入bash界面了
继续流处理wordcount:
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.api.scala._
object StreamWC {
def main(args: Array[String]): Unit = {
val env = StreamExecutionEnvironment.getExecutionEnvironment
val inputDataStream=env.socketTextStream("localhost",9999)
val result=inputDataStream.flatMap(_.split(" ")).map((_,1)).keyBy(0).sum(1)
result.print()
env.execute()
}
}
运行,观察执行情况:
完成