flink dataStream

2020-08-24  本文已影响0人  程序男保姆

dataSource 数据来源

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment  env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.socketTextStream("localhost",8888).print();
        env.execute("demo");
    }

time 时间

windows 窗口

翻滚窗口(Tumbling Window,无重叠)
滚动窗口(Sliding Window,有重叠)
会话窗口(Session Window,活动间隙)
全局窗口

              // 设置窗口时间为 处理时间
                .window(TumblingProcessingTimeWindows.of(Time.seconds(10)))
              // 设置窗口时间为 事件时间
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))

windowsAll

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        env.setParallelism(1);

        DataStreamSource<String> streamSource1 = env.socketTextStream("localhost", 8888);


        streamSource1
                .map(new MapFunction<String, Tuple3<String, Long, Integer>>() {
                    @Override
                    public Tuple3<String, Long, Integer> map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new Tuple3<>(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                })
                // 设置处理事件为事件时间必须指定时间与水位线
                .assignTimestampsAndWatermarks(new AssignerWithPeriodicWatermarks<Tuple3<String, Long, Integer>>() {
                    private long currentTimestamp = Long.MIN_VALUE;

                    private String sdf = "yyyy-MM-dd HH:mm:ss";

                    @Override
                    public long extractTimestamp(Tuple3<String, Long, Integer> word, long previousElementTimestamp) {

                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(sdf);

                        long timestamp = word.f1;
                        currentTimestamp = currentTimestamp > timestamp ? currentTimestamp : timestamp;
                        System.out.println("event " +
                                "timestamp = {" + timestamp + "}, {" + simpleDateFormat.format(new Date(timestamp)) + "}, " +
                                "CurrentWatermark = {" + getCurrentWatermark().getTimestamp() + "}, {" + simpleDateFormat.format(new Date(currentTimestamp)) + "}");

                        // 这里特别注意下 timestamp 是
                        //当前对象的时间毫秒值
                        //当前对象的时间毫秒值
                        //当前对象的时间毫秒值
                        return timestamp;
                    }

                    @Nullable
                    @Override
                    public Watermark getCurrentWatermark() {
                        long maxTimeLag = 0;
                        long lastEmittedWatermark = currentTimestamp == Long.MIN_VALUE ? Long.MIN_VALUE : currentTimestamp - maxTimeLag;
                        return new Watermark(lastEmittedWatermark);
                    }
                })
                // 设置窗口为事件时间翻滚
                //.windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                // 设置窗口为处理时间翻滚
                //.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
                // 设置窗口为事件时间滚动 每三秒统计一次五分钟的数据
                .windowAll(SlidingEventTimeWindows.of(Time.seconds(5),Time.seconds(3)))
                // 设置窗口为处理时间滚动
                //.windowAll(SlidingProcessingTimeWindows.of(Time.seconds(5)))
                .apply(new AllWindowFunction<Tuple3<String, Long, Integer>, Tuple3<Long, Long, Integer>, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow
                                              window, Iterable<Tuple3<String, Long, Integer>> values, Collector<Tuple3<Long, Long, Integer>> out) throws
                            Exception {
                        int sum = StreamSupport.stream(values.spliterator(), false).mapToInt(o -> o.f2).sum();
                        long start = window.getStart();
                        long end = window.getEnd();
                        out.collect(new Tuple3<>(start, end, sum));
                    }
                }).

                print();

        env.execute("demo");

    }

Watermark 水位线

// 添加水位线
.assignTimestampsAndWatermarks(new WordPeriodicWatermark())


public class WordPeriodicWatermark implements AssignerWithPeriodicWatermarks<Word> {

    private long currentTimestamp = Long.MIN_VALUE;

    private static String sdf = "yyyy-MM-dd HH:mm:ss";

    @Override
    public long extractTimestamp(Word word, long previousElementTimestamp) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(sdf);


        long timestamp = word.getTimestamp();
        currentTimestamp = currentTimestamp > word.getTimestamp() * 1000 ? currentTimestamp : word.getTimestamp() * 1000;
        System.out.println("event " +
                "timestamp = {" + word.getTimestamp() + "}, {" + simpleDateFormat.format(new Date(timestamp * 1000)) + "}, " +
                "CurrentWatermark = {" + getCurrentWatermark().getTimestamp() + "}, {" + simpleDateFormat.format(new Date(currentTimestamp)) + "}");

       // 这里特别注意下 timestamp 是 
      //当前对象的时间毫秒值 
      //当前对象的时间毫秒值 
      //当前对象的时间毫秒值
        return timestamp * 1000;
    }

    @Nullable
    @Override
    public Watermark getCurrentWatermark() {
        long maxTimeLag = 2000;
        long lastEmittedWatermark = currentTimestamp == Long.MIN_VALUE ? Long.MIN_VALUE : currentTimestamp - maxTimeLag;

        return new Watermark(lastEmittedWatermark);
    }
}

举个例子,最简单的水位线算法就是取目前为止最大的事件时间,然而这种方式比较暴力,对乱序事件的容忍程度比较低,容易出现大量迟到事件。

算子

  
    public class JoinDemo {
    private static long currentTimestamp = Long.MIN_VALUE;

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        env.setParallelism(1);

        AssignerWithPeriodicWatermarks<Tuple3<String, Long, Integer>> timestampAndWatermarkAssignerssss = new TimestampAndWatermarkAssignerssss();

        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> streamSource1 = env.socketTextStream("localhost", 8888)
                .map(new MapFunction<String, Tuple3<String, Long, Integer>>() {
                    @Override
                    public Tuple3<String, Long, Integer> map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new Tuple3<>(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                }).assignTimestampsAndWatermarks(timestampAndWatermarkAssignerssss);
        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> streamSource2 = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple3<String, Long, Integer>>() {
                    @Override
                    public Tuple3<String, Long, Integer> map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new Tuple3<>(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
                    }
                }).assignTimestampsAndWatermarks(timestampAndWatermarkAssignerssss);
        ;


        streamSource1
                .join(streamSource2)
                .where(new KeySelector<Tuple3<String, Long, Integer>, Long>() {
                    @Override
                    public Long getKey(Tuple3<String, Long, Integer> value) throws Exception {
                        System.out.println("ss1 = " + value);
                        return value.f1;
                    }
                })
                .equalTo(new KeySelector<Tuple3<String, Long, Integer>, Long>() {
                    @Override
                    public Long getKey(Tuple3<String, Long, Integer> value) throws Exception {
                        System.out.println("ss2 = " + value);
                        return value.f1;
                    }
                })
                // 设置窗口时间为 事件时间 这个时间控制隔多少时间内触发join
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .apply(new JoinFunction<Tuple3<String, Long, Integer>, Tuple3<String, Long, Integer>, Tuple3<String, Long, String>>() {
                    @Override
                    public Tuple3<String, Long, String> join(Tuple3<String, Long, Integer> first, Tuple3<String, Long, Integer> second) throws Exception {

                        System.out.println("first = " + first.toString());
                        System.out.println("second = " + second.toString());

                        return new Tuple3<>(first.f0, first.f1, " (" + first.f2 + "" + second.f2 + ") ");
                    }
                })
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .apply(new AllWindowFunction<Tuple3<String, Long, String>, Tuple3<Long, Long, String>, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<Tuple3<String, Long, String>> values, Collector<Tuple3<Long, Long, String>> out) throws Exception {
                        String collect = StreamSupport.stream(values.spliterator(), false).map(o -> {
                            System.out.println("apply = " + o.toString());
                            return o.f2;
                        }).collect(Collectors.joining(","));
                        long start = window.getStart();
                        long end = window.getEnd();
                        out.collect(new Tuple3<>(start, end, collect));
                    }
                })
                .print();

        env.execute("de");

    }


    private static class TimestampAndWatermarkAssignerssss implements AssignerWithPeriodicWatermarks<Tuple3<String, Long, Integer>> {

        private String sdf = "yyyy-MM-dd HH:mm:ss";

        @Override
        public long extractTimestamp(Tuple3<String, Long, Integer> word, long previousElementTimestamp) {

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(sdf);

            long timestamp = word.f1;
            currentTimestamp = currentTimestamp > timestamp ? currentTimestamp : timestamp;
            System.out.println("event " +
                    "timestamp = {" + timestamp + "}, {" + simpleDateFormat.format(new Date(timestamp)) + "}, " +
                    "CurrentWatermark = {" + getCurrentWatermark().getTimestamp() + "}, {" + simpleDateFormat.format(new Date(currentTimestamp)) + "}");

            // 这里特别注意下 timestamp 是
            //当前对象的时间毫秒值
            //当前对象的时间毫秒值
            //当前对象的时间毫秒值
            return timestamp;
        }

        @Nullable
        @Override
        public Watermark getCurrentWatermark() {
            long maxTimeLag = 0;
            long lastEmittedWatermark = currentTimestamp == Long.MIN_VALUE ? Long.MIN_VALUE : currentTimestamp - maxTimeLag;
            return new Watermark(lastEmittedWatermark);
        }
    }
}

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env.socketTextStream("localhost", 8888)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] split = value.split(",");
                        Arrays.stream(split).forEach(o -> {
                            out.collect(new Tuple2<>(o, 1));
                        });
                    }
                })
                .keyBy(0)
//                .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
////                    @Override
////                    public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
////                        return new Tuple2<>(value1.f0, value1.f1 + value2.f1);
////                    }
////                })
////
                .sum(1)



//                .keyBy(0)
//                .countWindow(5)
//                .apply(new WindowFunction<Tuple2<String, Integer>, Tuple2<String, String>, Tuple, GlobalWindow>() {
//                    @Override
//                    public void apply(Tuple tuple, GlobalWindow window, Iterable<Tuple2<String, Integer>> input, Collector<Tuple2<String, String>> out) throws Exception {
//                        Tuple2<String, Integer> sss = StreamSupport.stream(input.spliterator(), false).findFirst().get();
//                        String collect = StreamSupport.stream(input.spliterator(), false).map(o -> o.f1 + "").collect(Collectors.joining(" = "));
//
//                        out.collect(new Tuple2<>(sss.f0,collect));
//                    }
//                })
                .print();

        env.execute("aaa");

    }

public class SplitDemo {

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

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);


        SplitStream<Integer> split = env.socketTextStream("localhost", 8888)
                .map(Integer::valueOf)
                .split(new OutputSelector<Integer>() {
                    @Override
                    public Iterable<String> select(Integer value) {
                        List<String> output = new ArrayList<String>();
                        if (value % 2 == 0) {
                            output.add("even");
                        } else {
                            output.add("odd");
                        }
                        return output;
                    }
                });

        DataStream<Integer> even = split.select("even");

        even.process(new ProcessFunction<Integer, String>() {
            @Override
            public void processElement(Integer value, Context ctx, Collector<String> out) throws Exception {
                out.collect("even "+value);
            }
        }).print();

        DataStream<Integer> odd = split.select("odd");

        odd.process(new ProcessFunction<Integer, String>() {
            @Override
            public void processElement(Integer value, Context ctx, Collector<String> out) throws Exception {
                out.collect("odd "+value);
            }
        }).print();


        env.execute("ss");

    }
}

state 状态

sink

上一篇 下一篇

猜你喜欢

热点阅读