一:安装
# 安装
brew install apache-flink
# 查看版本号
flink --version
# 查看安装位置
brew info apache-flink
# 启动Flink(启动后可以访问 http://localhost:8081/ )
./libexec/bin/start-cluster.sh
二:Java HelloWorld
示例功能:监听netcat输入的字符,然后进行聚合操作,最后输出字符统计。
1. 创建Flink Project
方式一:使用IDEA创建工程
1.1 新增Flink对应的Maven骨架
- GroupId: 固定值 org.apache.flink
- ArtifactId:固定值 flink-quickstart-java
- Version:Flink的版本号,写自己安装的Flink对应的版本号
1.2 新建Maven工程选择flink-quickstart-java
方式二:使用mvn命令创建工程
mvn archetype:generate
-DarchetypeGroupId=org.apache.flink
-DarchetypeArtifactId=flink-quickstart-java
-DarchetypeVersion=1.9.1
-DgroupId=com.example
-DartifactId=flink-helloworld
-Dversion=1.0
-Dpackage=com.example.helloworld
-DinteractiveMode=false
2. SocketTextStreamWordCount
package com.example.helloworld;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;
public class SocketTextStreamWordCount {
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println("USAGE:\\nSocketTextStreamWordCount <hostname> <port>");
return;
}
String hostName = args[0];
Integer port = Integer.parseInt(args[1]);
StreamExecutionEnvironment environment = StreamExecutionEnvironment.getExecutionEnvironment();
DataStreamSource<String> text = environment.socketTextStream(hostName, port);
DataStream<Tuple2<String, Integer>> counts = text.flatMap(new LineSplitter()).keyBy(0).sum(1);
counts.print();
environment.execute("Java WordCount from SocketTextStream Example");
}
public static final class LineSplitter implements FlatMapFunction<String, Tuple2<String, Integer>> {
@Override
public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
String[] tokens = s.toLowerCase().split("\\W+");
for (String token : tokens) {
if (token.length() > 0) {
collector.collect(new Tuple2<String, Integer>(token, 1));
}
}
}
}
}
3. 打包maven工程
打包maven工程可以通过IDEA自带的窗口也可以直接使用maven命令
maven clean package -Dmaven.test.skip=true
4. 监听9000端口
nc是netcat的简写,有着网络界的瑞士军刀的美誉。因为它短小精悍、功能实用,被设计为一个简单、可靠的网络工具。-l:用于指定nc将处于侦听模式。指定该参数,则意味着nc被当作server,侦听并接受连接,而非向其它地址发起连接。
nc -l 9000
5. 运行程序
flink run -c com.example.helloworld.SocketTextStreamWordCount
flink-helloworld-1.0-SNAPSHOT.jar
127.0.0.1 9000
# *要替换成自己的用户名
tail -f ./libexec/log/flink-*-taskexecutor-1-localhost.out
在nc窗口中输入单词或者句子,在flink-*-taskexecutor-1-localhost.out文件中查看统计结果。