创建 Flink 项目
Flink 官方提供了 Flink Maven Archetype 工具,能够快速创建一个包含了必要依赖的 Flink 程序骨架,包括flink 的核心依赖 flink-streaming-java 它提供了 Flink 流式计算的核心api
mvn archetype:generate \
-DarchetypeGroupId=org.apache.flink \
-DarchetypeArtifactId=flink-walkthrough-datastream-java \
-DarchetypeVersion=1.11.2 \
-DgroupId=frauddetection \
-DartifactId=frauddetection \
-Dversion=0.1 \
-Dpackage=spendreport \
-DinteractiveMode=false
编写处理逻辑
每一个 mian 方法都对应 一个 Flink job 的入口,如果你有多个任务,就需要定义多个 main 方法
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
/**
* Flink 入门 单词统计
*/
public class WordCount {
public static void main(String[] args) throws Exception{
compute();
}
public static void compute() throws Exception{
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(1);
DataStreamSource<String> streamSource = env.readTextFile("D:/word.txt");
streamSource.flatMap(new FlatMapFunction<String, Tuple2<String, Long>>() {
@Override
public void flatMap(String value, Collector<Tuple2<String, Long>> out) throws Exception {
String[] words = value.split(" ");
for (String word : words){
out.collect(Tuple2.of(word, 1L));
Thread.sleep(1000);
}
}
})
.keyBy(t -> t.f0)
.sum(1)
.print();
env.execute("word count job");
}
}
这样就创建好了一个叫 word count job 的应用,你可以直接运行 mian 方法在本地进行调试,确认无误后打包
打包 Flink 程序
官方推荐我们使用 maven-shade-plugin 插件,复制一下代码到 POM 中指定我们的主方法类即可。
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<artifactSet>
<excludes>
<exclude>com.google.code.findbugs:jsr305</exclude>
<exclude>org.slf4j:*</exclude>
<exclude>log4j:*</exclude>
</excludes>
</artifactSet>
<filters>
<filter>
<!-- Do not copy the signatures in the META-INF folder.
Otherwise, this might cause SecurityExceptions when using the JAR. -->
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<!-- 设置jar包的入口类,也可以再提交任务时,手动指定 -->
<mainClass>com.wqlm.Flink.job.WordCount</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
执行
mvn clean package -DskipTests
提交任务
Flink 提供了web ui 供我们管理flink,我们可以通过 web 提交任务,先上传jar包后,对 job 进行配置
也可以选择使用 Flink Cli 提交任务,先将 jar 包上传到服务器,然后
./bin/flink run -c com.wqlm.Flink.job.WordCount \
./examples/batch/WordCount.jar \
--input file:///home/user/hamlet.txt --output file:///home/user/wordcount_out
其中 com.wqlm.Flink.job.WordCount job 的入口
操作完成后,可以去web页面查看提交结果