1. 程式人生 > >《Flink官方文件》Quick Start

《Flink官方文件》Quick Start

原文連結  譯者:清英

安裝: 下載並開始使用Flink

Flink 可以執行在 Linux, Mac OS X和Windows上。為了執行Flink, 唯一的要求是必須在Java 7.x (或者更高版本)上安裝。Windows 使用者, 請檢視 Flink在Windows上的安裝指南。

你可以使用以下命令檢查Java當前執行的版本:

java -version

如果你有安裝Java 8,命令列有如下回顯

java version "1.8.0_111"

Java(TM) SE Runtime Environment (build 1.8.0_111-b14)

Java HotSpot(TM) 64-Bit Server VM (build 25.111-b14, mixed mode)

** 下載和解壓 **

  1. 下載頁下載一個二進位制的包,你可以選擇任何你喜歡的Hadoop/Scala組合包。如果你計劃使用檔案系統,那麼可以使用任何Hadoop版本。
  2. 進入下載目錄
  3. 解壓下載的壓縮包
$ cd ~/Downloads        # Go to download directory
$ tar xzf flink-*.tgz   # Unpack the downloaded archive
$ cd flink-1.2.0
Start a Local Flink Cluster

MacOS X

對於 MacOS X 使用者, Flink 可以通過Homebrew 進行安裝。

 ~~~bash 
 $ brew install apache-flink … 
 $ flink –version 
 Version: 1.2.0, Commit ID: 1c659cf ~~~

啟動一個本地的Flink叢集

使用如下命令啟動Flink:

$ ./bin/start-local.sh  # Start Flink

通過訪問http://localhost:8081檢查JobManager網頁,確保所有元件都已執行。網頁會顯示一個有效的TaskManager例項。
jobmanager-1.png

譯註:本地需要有localhost 127.0.0.1的域名對映

你也可以通過檢查日誌目錄裡的日誌檔案來驗證系統是否已經執行:


$ tail log/flink-*-jobmanager-*.log
INFO ... - Starting JobManager
INFO ... - Starting JobManager web frontend
INFO ... - Web frontend listening at 127.0.0.1:8081
INFO ... - Registered TaskManager at 127.0.0.1 (akka://flink/user/taskmanager)

閱讀原始碼

你可以在GitHub中找到SocketWindowWordCount完整的程式碼,有JAVASCALA兩個版本。

Scala


object SocketWindowWordCount {

    def main(args: Array[String]) : Unit = {

        // the port to connect to
        val port: Int = try {
            ParameterTool.fromArgs(args).getInt("port")
        } catch {
            case e: Exception => {
                System.err.println("No port specified. Please run 'SocketWindowWordCount --port <port>'")
                return
            }
        }

        // get the execution environment
        val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

        // get input data by connecting to the socket
        val text = env.socketTextStream("localhost", port, '\n')

        // parse the data, group it, window it, and aggregate the counts
        val windowCounts = text
            .flatMap { w => w.split("\\s") }
            .map { w => WordWithCount(w, 1) }
            .keyBy("word")
            .timeWindow(Time.seconds(5), Time.seconds(1))
            .sum("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
    case class WordWithCount(word: String, count: Long)
}

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;
        }
    }
}

執行例子

現在, 我們可以執行Flink 應用程式。 這個例子將會從一個socket中讀一段文字,並且每隔5秒列印每個單詞出現的數量。 例如 a tumbling window of processing time, as long as words are floating in.

  • 第一步, 我們可以通過netcat命令來啟動本地服務。
$ nc -l 9000

提交Flink程式:

$ ./bin/flink run examples/streaming/SocketWindowWordCount.jar --port 9000


Cluster configuration: Standalone cluster with JobManager at /127.0.0.1:6123
Using address 127.0.0.1:6123 to connect to JobManager.
JobManager web interface address http://127.0.0.1:8081
Starting execution of program
Submitting job with JobID: 574a10c8debda3dccd0c78a3bde55e1b. Waiting for job completion.
Connected to JobManager at Actor[akka.tcp://[email protected]:6123/user/jobmanager#297388688]
11/04/2016 14:04:50     Job execution switched to status RUNNING.
11/04/2016 14:04:50     Source: Socket Stream -> Flat Map(1/1) switched to SCHEDULED
11/04/2016 14:04:50     Source: Socket Stream -> Flat Map(1/1) switched to DEPLOYING
11/04/2016 14:04:50     Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to SCHEDULED
11/04/2016 14:04:51     Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to DEPLOYING
11/04/2016 14:04:51     Fast TumblingProcessingTimeWindows(5000) of WindowedStream.main(SocketWindowWordCount.java:79) -> Sink: Unnamed(1/1) switched to RUNNING
11/04/2016 14:04:51     Source: Socket Stream -> Flat Map(1/1) switched to RUNNING

譯者注:你也可以提交一個簡單的任務examples/batch/WordCount.jar任務,也可以介面提交任務,提交前需要選擇一下Entry Class。

程式連線socket並等待輸入,你可以通過web介面來驗證任務期望的執行結果:

jobmanager-3.png

單詞的數量在5秒的時間視窗中進行累加(使用處理時間和tumbling視窗),並列印在stdout。監控JobManager的輸出檔案,並在nc寫一些文字(回車一行就傳送一行輸入給Flink) :

$ nc -l 9000
lorem ipsum
ipsum ipsum ipsum
bye

譯者注:mac下使用命令nc -l -p 9000來啟動監聽埠,如果有問題可以telnet localhost 9000看下監聽埠是否已經啟動,如果啟動有問題可以重灌netcat ,使用命令brew install netcat

.out檔案將被列印每個時間視窗單詞的總數:

$ tail -f log/flink-*-jobmanager-*.out
lorem : 1
bye : 1
ipsum : 4

使用以下命令來停止Flink:

$ ./bin/stop-local.sh

下一步

Check out更多的例子來熟悉Flink的程式設計API。 當你完成這些,可以繼續閱讀streaming指南


方 騰飛

花名清英,併發網(ifeve.com)創始人,暢銷書《Java併發程式設計的藝術》作者,螞蟻金服技術專家。目前工作於支付寶微貸事業部,關注網際網路金融,併發程式設計和敏捷實踐。微信公眾號aliqinying。