flink小例子

1,366 阅读3分钟

##首先确定安装了jdk

如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)

下载

wget mirrors.tuna.tsinghua.edu.cn/apache/flin…

解压

tar -zxvf flink-1.8.2-bin-scala_2.12.tgz

启动

cd flink-1.8.2-bin-scala_2.12

./bin/start-cluster.sh

查看启动效果

在http://localhost:8081上检查Dispatcher的Web前端,并确保一切正常并正在运行。Web前端应报告一个可用的TaskManager实例。

或者通过下面查看日志方式看是否成功启动:

 tail flink-*-standalonesession-*.log
2019-10-29 10:50:35,563 INFO  org.apache.flink.runtime.dispatcher.DispatcherRestEndpoint    - http://localhost:8081 was granted leadership with leaderSessionID=00000000-0000-0000-0000-000000000000
2019-10-29 10:50:35,563 INFO  org.apache.flink.runtime.dispatcher.DispatcherRestEndpoint    - Web frontend listening at http://localhost:8081.
2019-10-29 10:50:36,503 INFO  org.apache.flink.runtime.rpc.akka.AkkaRpcService              - Starting RPC endpoint for org.apache.flink.runtime.resourcemanager.StandaloneResourceManager at akka://flink/user/resourcemanager .
2019-10-29 10:50:36,661 INFO  org.apache.flink.runtime.rpc.akka.AkkaRpcService              - Starting RPC endpoint for org.apache.flink.runtime.dispatcher.StandaloneDispatcher at akka://flink/user/dispatcher .
2019-10-29 10:50:36,785 INFO  org.apache.flink.runtime.resourcemanager.StandaloneResourceManager  - ResourceManager akka.tcp://flink@localhost:6123/user/resourcemanager was granted leadership with fencing token 00000000000000000000000000000000
2019-10-29 10:50:36,869 INFO  org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager  - Starting the SlotManager.
2019-10-29 10:50:36,963 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Dispatcher akka.tcp://flink@localhost:6123/user/dispatcher was granted leadership with fencing token 00000000-0000-0000-0000-000000000000
2019-10-29 10:50:36,965 INFO  org.apache.flink.runtime.dispatcher.StandaloneDispatcher      - Recovering all persisted jobs.
2019-10-29 10:50:48,395 INFO  org.apache.flink.runtime.resourcemanager.StandaloneResourceManager  - Ignoring outdated TaskExecutorGateway connection.
2019-10-29 10:50:48,572 INFO  org.apache.flink.runtime.resourcemanager.StandaloneResourceManager  - Registering TaskManager with ResourceID 1793c0ec8b3c0617e2c3ea4091acdc69 (akka.tcp://flink@127.0.0.1:44941/user/taskmanager_0) at ResourceManager

编写测试例子

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;

import static org.apache.flink.streaming.api.windowing.time.Time.seconds;


/**
 * @author huangyiminghappy@163.com
 * @className: SocketWindowWordCount
 * @description: TODO
 * @date 2019-10-29
 */
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( seconds(5), 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;
        }
    }
}

服务端测试

  • 运行 nc -l 0.0.0.0 9000

  • 把刚才测试代码达成jar包运行:

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

查看效果


nc -l 0.0.0.0 9000
lorem ipsum
ipsum ipsum ipsum
bye
tail -f log/flink-*-taskexecutor-*.out
lorem : 1
bye : 1
ipsum : 4