安裝查看 Java 的版本號,推薦使用 Java 8。java
一、在 Mac OS X 上安裝 Flink 是很是方便的。推薦經過 homebrew 來安裝。web
brew install apache-flink
二、檢查安裝:apache
flink --version
結果:api
Version: 1.6.0, Commit ID: ff472b4
三、啓動 flinksession
zhisheng@zhisheng /usr/local/Cellar/apache-flink/1.6.0/libexec/bin ./start-cluster.sh Starting cluster. Starting standalonesession daemon on host zhisheng. Starting taskexecutor daemon on host zhisheng.
接着就能夠進入 web 頁面(http://localhost:8081/) 查看socket
一、新建一個 maven 項目maven
建立一個 SocketTextStreamWordCount 文件,加入如下代碼:ide
package com.zhisheng.flink; 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.datastream.SingleOutputStreamOperator; import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment; import org.apache.flink.util.Collector; /** * Created by zhisheng_tian on 2018/9/18 */ 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]); // set up the streaming execution environment final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); //獲取數據 DataStreamSource<String> stream = env.socketTextStream(hostname, port); //計數 SingleOutputStreamOperator<Tuple2<String, Integer>> sum = stream.flatMap(new LineSplitter()) .keyBy(0) .sum(1); sum.print(); env.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) { String[] tokens = s.toLowerCase().split("\\W+"); for (String token: tokens) { if (token.length() > 0) { collector.collect(new Tuple2<String, Integer>(token, 1)); } } } } }
接着進入工程目錄,使用如下命令打包。spa
mvn clean package -Dmaven.test.skip=true
而後咱們開啓監聽 9000 端口:3d
nc -l 9000
最後進入 flink 安裝目錄 bin 下執行如下命令跑程序:
flink run -c com.zhisheng.flink.SocketTextStreamWordCount /Users/zhisheng/IdeaProjects/flink/word-count/target/original-word-count-1.0-SNAPSHOT.jar 127.0.0.1 9000
注意換成你本身項目的路徑。
執行完上述命令後,咱們能夠在 webUI 中看到正在運行的程序:
咱們能夠在 nc 監聽端口中輸入 text,好比:
而後咱們經過 tail 命令看一下輸出的 log 文件,來觀察統計結果。進入目錄 apache-flink/1.6.0/libexec/log,執行如下命令:
tail -f flink-zhisheng-taskexecutor-0-zhisheng.out
注意:切換成你本身的路徑和查看本身的目錄。
本文描述瞭如何在 Mac 電腦上安裝 Flink,及運行它。接着經過一個簡單的 Flink 程序來介紹如何構建及運行Flink 程序。