FLINK实例

public class StreamTest{
    public static void main(String[] args) throws Exception{
        final StreamExecutionEnvironment env= StreamExecutionEnvironment.getExecutionEnvironment();
        //******************************source*********************************************
        //自定义数据源SourceFunction RichParallelSourceFunction
        DataStreamSource<Tuple2<String, Long>> ds=env.addSource(new SourceFunction<Tuple2<String, Long>>(){//
            private Long count=1L;
            private boolean flag=true;
            @Override
            public void run(SourceContext sourceContext) throws Exception {

                while(flag){
                    Tuple2<String, Long> t=null;
                    if(count%2==0){
                        t=new Tuple2<String, Long>("A",count);
                    }else
                        t=new Tuple2<String, Long>("B",count);
                    sourceContext.collect(t);
                    count++;
                    Thread.sleep(1000);
                }
            }
            @Override
            public void cancel() {
                flag=false;
            }
        }).setParallelism(1);//自定义单一分区数据源
        DataStream<Tuple2<String, Long>> dst=ds.map((l)->{
            System.out.println(l);
            return  l;}).returns(Types.TUPLE(Types.STRING, Types.LONG));
        DataStream sum=dst.keyBy(0).timeWindow(Time.seconds(2))
        //DataStream sum=dst.keyBy(0).timeWindowAll(Time.seconds(2)).sum(1);//keyby无效
        //keyby
                /**自定义实体类keyby指定方法
                 * .keyBy(new KeySelector<ProductViewData, String>() {
                             @Override
                             public String getKey(ProductViewData value) throws Exception {
                                 return value.productId;
                             }
                             //时间窗口 6秒  滑动间隔3秒
                         })
                 */
          .sum(1);
          .reduce((t2,t3)->{ //三个参数类型必须一致
              return  new Tuple2<>(t2.f0,t2.f1+t3.f1);
          }).returns(Types.TUPLE(Types.STRING, Types.LONG));
        sum.print();
        env.execute(StreamTest.class.getSimpleName());

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值