First demo of Flink
参考官方教程 https://ci.apache.org/projects/flink/flink-docs-release-1.7/tutorials/local_setup.html
macOS 可以使用 brew install apache-flink
直接安装。
不过我这里直接下载二进制包来测试。
此处不再赘述去官方下载二进制包和解压的步骤。
PS:我用的是 1.7.2 版本。
在本地启动
$ ./bin/start-cluster.sh # Start Flink
可以看到已经启动起来了。
在浏览器打开 http://localhost:8081/#/overview
可以看到效果。
查看日志
tail log/flink-tony-standalonesession-0-TMBP.local.log
测试第一个程序 wordcount
java 代码:
public class SocketWindowWordCount {
public static void main(String[] args) throws Exception {
// the port to connect to
final int port;
try {
final ParameterTool params = ParameterTool.fromArgs(args);
port = params.getInt("port");
} catch (Exception e) {
System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'");
return;
}
// get the execution environment
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
// get input data by connecting to the socket
DataStream<String> text = env.socketTextStream("localhost", port, "\n");
// parse the data, group it, window it, and aggregate the counts
DataStream<WordWithCount> windowCounts = text
.flatMap(new FlatMapFunction<String, WordWithCount>() {
@Override
public void flatMap(String value, Collector<WordWithCount> out) {
for (String word : value.split("\\s")) {
out.collect(new WordWithCount(word, 1L));
}
}
})
.keyBy("word")
.timeWindow(Time.seconds(5), Time.seconds(1))
.reduce(new ReduceFunction<WordWithCount>() {
@Override
public WordWithCount reduce(WordWithCount a, WordWithCount b) {
return new WordWithCount(a.word, a.count + b.count);
}
});
// print the results with a single thread, rather than in parallel
windowCounts.print().setParallelism(1);
env.execute("Socket Window WordCount");
}
// Data type for words with count
public static class WordWithCount {
public String word;
public long count;
public WordWithCount() {}
public WordWithCount(String word, long count) {
this.word = word;
this.count = count;
}
@Override
public String toString() {
return word + " : " + count;
}
}
}
编译成 jar 包(examples/streaming/ 目录下有现成的 SocketWindowWordCount.jar)
首先用 netcat 启动一个本地的 server
nc -l 9001 (由于我的本机 9000 端口被其他应用占用了,改用 9001)
然后提交 flink 应用侦听 9001
./bin/flink run examples/streaming/SocketWindowWordCount.jar --port 9001
开始测试:
由于是按时间窗口来统计的,所以输入较快的时候(5秒内输入多次),可以看到 hello world 统计出来的效果