天天看點

flink掃盲-DataStream中資料源API實驗

文章目錄

      • 直接輸入形式
        • fromElements
        • fromCollection
      • Socket形式
      • 檔案形式
      • 自定義形式

下面針對DataStream中資料流向API的資料源進行實驗

直接輸入形式

fromElements

step1:編寫程式

ElementsInput.java

package org.myorg.quickstart;

import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author ryan create on 2019/1/6
 **/
public class ElementsInput {
    public static void main(String[] args) throws Exception {
        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // string Elements

        String inputText1 = "hey, man, this is collection are you ok?";
        String inputText2 = "hello flink, this is string";

        DataStreamSource<String> text = env.fromElements(inputText1, inputText2);

        // parse the data, group it, window it, and aggregate the counts
        text.print();

        /**
         * 2> hello flink, this is string
         * 1> hey, man, this is collection are you ok?
         */

        // print the results with a single thread, rather than in parallel
        env.execute();
    }
}

           

step2:編譯并啟動程式

mvn clean package
mvn exec:java -Dexec.mainClass=org.myorg.quickstart.ElementsInput 

           

頁面直接列印

1> hey, man, this is collection are you ok?
2> hello flink, this is string
           

fromCollection

step1:編寫程式

CollectionInput.java

package org.myorg.quickstart;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @author ryan 
 **/
public class CollectionInput {
    public static void main(String[] args) throws Exception {
        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();



        DataStreamSource<String> text = env.fromCollection(new ArrayList<String>(Arrays.asList("Hi", "legotime", "ok")));
        text.map(new MapFunction<String, Void>() {
            @Override
            public Void map(String s) throws Exception {
                System.out.println(s);
                return null;
            }
        });


        // print the results with a single thread, rather than in parallel
        env.execute();
    }
}

           

step2:編譯并啟動程式

mvn clean package
mvn exec:java -Dexec.mainClass=org.myorg.quickstart.CollectionInput 

           

列印

Hi
legotime
ok
           

Socket形式

step1:編寫程式

SocketWindowWordCount.java

package org.myorg.quickstart;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;

/**
 * Implements a streaming windowed version of the "WordCount" program.
 *
 * <p>This program connects to a server socket and reads strings from the socket.
 * The easiest way to try this out is to open a text server (at port 12345)
 * using the <i>netcat</i> tool via
 * <pre>
 * nc -l 12345
 * </pre>
 * and run this example with the hostname and the port as arguments.
 */
@SuppressWarnings("serial")
public class SocketWindowWordCount {

    public static void main(String[] args) throws Exception {

        // the host and the port to connect to
        final String hostname;
        final int port;
        try {
            final ParameterTool params = ParameterTool.fromArgs(args);
            hostname = params.has("hostname") ? params.get("hostname") : "localhost";
            port = params.getInt("port");
        } catch (Exception e) {
            System.err.println("No port specified. Please run 'SocketWindowWordCount " +
                    "--hostname <hostname> --port <port>', where hostname (localhost by default) " +
                    "and port is the address of the text server");
            System.err.println("To start a simple text server, run 'netcat -l <port>' and " +
                    "type the input text into the command line");
            return;
        }

        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        // get input data by connecting to the socket
        DataStream<String> text = env.socketTextStream(hostname, 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))

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

step2:啟動一個socket端口

nc -l 12345
           

step3:編譯并啟動程式

mvn clean package
mvn exec:java -Dexec.mainClass=org.myorg.quickstart.SocketWindowWordCount -Dexec.args="--hostname 127.0.0.1  --port 12345"

           

step4:socket端口輸入資料

➜  tmp nc -l 12345
this is socket
pretty test
           

得到程式中如下結果

this : 1
is : 1
socket : 1
pretty : 1
test : 1
           

檔案形式

step1:編寫程式

FileInput.java

package org.myorg.quickstart;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;


/**
 * @author ryan 
 **/
public class FileInput {
    public static void main(String[] args) throws Exception {
        // get the execution environment
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> text = env.readTextFile("tmp.txt");


        text.map(new MapFunction<String, Void>() {
            @Override
            public Void map(String s) throws Exception {
                System.out.println(s);
                return null;
            }
        });


        // print the results with a single thread, rather than in parallel
        env.execute();
    }
}

           

step3:編譯并啟動程式

mvn clean package
echo "this is tmp file " > tmp.txt
mvn exec:java -Dexec.mainClass=org.myorg.quickstart.SocketWindowWordCount -Dexec.args="--hostname 127.0.0.1  --port 12345"
           

終端輸出:

自定義形式

自定義的形式可以是其他的一些資料源,比如kafka,等接下來的

connector

環境會對其進行詳細說明

繼續閱讀