欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

flink-reduce

程序员文章站 2022-06-07 23:02:49
...

一.背景

     有时候我们需要过滤数据,有些中间数据是不需要的,比如场景:

     binlog 数据更新的时候,我们仅仅需要最新数据。会根据ID 分组,然后取version 最大的一条,存储

 

二.简单实例

  

@Data
@ToString
public class Order {
    // 主键id
    private Integer id;
    // 版本
    private Integer version;
    private Timestamp mdTime;

    public Order(int id, Integer version) {
        this.id = id;
        this.version = version;
        this.mdTime = new Timestamp(System.currentTimeMillis());
    }

    public Order() {
    }
}

 

 

public class OrderSource implements SourceFunction<Order> {
    Random random = new Random();

    @Override
    public void run(SourceContext<Order> ctx) throws Exception {
        while (true) {
            TimeUnit.MILLISECONDS.sleep(100);
            // 为了区分,我们简单生0~2的id, 和版本0~99
            int id = random.nextInt(3);
            Order o = new Order(id, random.nextInt(100));
            ctx.collect(o);
        }
    }
    @Override
    public void cancel() {

    }
}

 

public class ReduceApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);
        DataStream<Order> userInfoDataStream = env.addSource(new OrderSource());

        DataStream<Order> timedData = userInfoDataStream.assignTimestampsAndWatermarks(new AscendingTimestampExtractor<Order>() {
            @Override
            public long extractAscendingTimestamp(Order element) {
                return element.getMdTime().getTime();
            }
        });

        SingleOutputStreamOperator<Order> reduce = timedData
                .keyBy("id")
                .timeWindow(Time.seconds(10), Time.seconds(5))
                .reduce((ReduceFunction<Order>) (v1, v2) -> v1.getVersion() >= v2.getVersion() ? v1 : v2);

        reduce.print();
        env.execute("test");
    }
}

 

结果:

Order(id=2, version=97, mdTime=2019-03-11 17:39:34.052)

Order(id=0, version=99, mdTime=2019-03-11 17:39:32.913)

Order(id=1, version=96, mdTime=2019-03-11 17:39:34.155)

Order(id=2, version=97, mdTime=2019-03-11 17:39:34.052)

Order(id=1, version=96, mdTime=2019-03-11 17:39:34.155)

Order(id=0, version=99, mdTime=2019-03-11 17:39:32.913)

 

这个会对同一个窗口做过滤,比如同步到另一个mysql,hdfs,就能减少数据量

 

 

 

相关标签: flink reduce