第 11 节 DataStream之自定义source

上篇:第 10 节 DataStream之source讲解(java)


DataStream之自定义source

第一种方式:

1、代码编写操作

MyNoParalleSource.java

package xuwei.custormSource;

import org.apache.flink.streaming.api.functions.source.SourceFunction;

/**
 * 自定义实现并行度为1的source
 *
 * 模拟产生从1开始递增的数字
 * 注意:
 * SourceFunction和SourceCourceContext都需要指定数据类型,如果不指定,代码将会报错
 */
public class MyNoParalleSource implements SourceFunction<Long> {

    private Long count=0L;

    private boolean isRunning=true;

    /**
     * 主要的分发
     * 启动一个Source
     * 大部分情况下,都需要在这个run方法中实现一个循环,这个就可以循环产生数据了
     * @param ctx
     * @throws Exception
     */
    @Override
    public void run(SourceContext<Long> ctx)throws Exception {
        while (isRunning){
           ctx.collect(count);
           count++;
           //每秒产生一条数据
            Thread.sleep(1000);

        }

    }

    /**
     * 取消一个cancel的时候会调用的方法
     */
    @Override
    public void cancel() {
      isRunning = false;
    }
}

主程序类

StreamingDemoWithMyNoParalleSource,java

package xuwei.custormSource;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * 使用并行度为1的source
 *
 */
public class StreamingDemoWithMyNoParalleSource  {
    public static void main(String[] args)throws Exception {
        //获取flink的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //获取数据源
         DataStreamSource<Long>text= env.addSource(new MyNoParalleSource()).setParallelism(1);//注意,针对此source,并行度只能设置为1
;

        DataStream<Long>num= text.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("接收到的数据"+value);
                return value;
            }
        });

        //每2秒钟处理一次数据
        DataStream<Long> sum = num.timeWindowAll(Time.seconds(2)).sum(0);

        //打印结果
        sum.print().setParallelism(1);

        String jobname = StreamingDemoWithMyNoParalleSource.class.getSimpleName();
        env.execute(jobname);

    }
}


控制台打印数据
在这里插入图片描述
不断循环产生数据


2、第二种方式:多并行度

MyParalleSource.java

package xuwei.custormSource;

import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;

/**
 * 自定义实现支持多并行度source
 */
public class MyParalleSource implements ParallelSourceFunction<Long> {
    private Long count=0L;

    private boolean isRunning=true;

    /**
     * 主要的分发
     * 启动一个Source
     * 大部分情况下,都需要在这个run方法中实现一个循环,这个就可以循环产生数据了
     * @param ctx
     * @throws Exception
     */

    @Override
    public void run(SourceContext<Long> ctx) throws Exception {
        while (isRunning){
            ctx.collect(count);
            count++;
            //每秒产生一条数据
            Thread.sleep(1000);

        }
    }

    /**
     * 取消一个cancel的时候会调用的方法
     */
    @Override
    public void cancel() {
        isRunning = false;
    }
}

StreamingDemoWithMyParalleSource.java

package xuwei.custormSource;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * 使用多并行度的source
 *
 */
public class StreamingDemoWithMyParalleSource {
    public static void main(String[] args)throws Exception {
        //获取flink的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //获取数据源
        DataStreamSource<Long>text= env.addSource(new MyParalleSource());//注意,针对此source,并行度只能设置为1

        DataStream<Long>num= text.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("接收到的数据"+value);
                return value;
            }
        });

        //每2秒钟处理一次数据
        DataStream<Long> sum = num.timeWindowAll(Time.seconds(2)).sum(0);

        //打印结果
        sum.print().setParallelism(1);

        String jobname = StreamingDemoWithMyParalleSource.class.getSimpleName();
        env.execute(jobname);

    }
}


控制台打印数据,根据自己电脑的CPU核数打印数据
在这里插入图片描述
也是,不断循环产生数据

当然,我们也可以自定义设置打印的核数,设置代码参数是:

DataStreamSource<Long>text= env.addSource(new MyParalleSource()).setParallelism(2);//注意,针对此source,并行度只能设置为1

重新运行,控制台打印数据是2核的并行度
在这里插入图片描述
当然,也是,不断循环产生数据


3、方式三:继承RichParallelSourceFunction

MyRichParalleSource .java

package xuwei.custormSource;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

/**
 * 自定义实现支持多并行度source
 * RichAggregateFunctiong会额外提供open和close方法
 * 针对source中如果要获取其他链接资源,那么可以在open方法中获取资源链接,在close中关闭资源链接
 */
public class MyRichParalleSource extends RichParallelSourceFunction<Long> {
    private Long count=0L;

    private boolean isRunning=true;

    /**
     * 主要的分发
     * 启动一个Source
     * 大部分情况下,都需要在这个run方法中实现一个循环,这个就可以循环产生数据了
     * @param ctx
     * @throws Exception
     */

    public void run(SourceFunction.SourceContext<Long> ctx) throws Exception {
        while (isRunning){
            ctx.collect(count);
            count++;
            //每秒产生一条数据
            Thread.sleep(1000);

        }
    }

    /**
     * 取消一个cancel的时候会调用的方法
     */

    public void cancel() {
        isRunning = false;
    }


    /**
     * 这个方法只会在最开始的时候被调用一次
     * 实现资源链接代码
     * @param parameters
     * @throws Exception
     */
    public void open(Configuration parameters) throws Exception {
        System.out.println("open..............");
        super.open(parameters);
    }

    /**
     * 实现关闭资源的代码
     * @throws Exception
     */
    public void close() throws Exception {
        super.close();
    }
}

StreamingDemoWithMyRichParalleSource .java

package xuwei.custormSource;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * 使用多并行度的source
 *
 */
public class StreamingDemoWithMyRichParalleSource {
    public static void main(String[] args)throws Exception {
        //获取flink的运行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //获取数据源
        DataStreamSource<Long>text= env.addSource(new MyRichParalleSource()).setParallelism(2);//注意,针对此source,并行度只能设置为1

        DataStream<Long>num= text.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("接收到的数据"+value);
                return value;
            }
        });

        //每2秒钟处理一次数据
        DataStream<Long> sum = num.timeWindowAll(Time.seconds(2)).sum(0);

        //打印结果
        sum.print().setParallelism(1);

        String jobname = StreamingDemoWithMyRichParalleSource.class.getSimpleName();
        env.execute(jobname);

    }
}


控制台打印数据,是2个线程,不断循环下去
在这里插入图片描述


3、总结

自定义source

实现并行度为1的自定义source

  1. 实现SourceFunction
  2. 一般不需要实现容错性保证
  3. 处理好cancel方法(cancel应用的时候,这个方法会被调用)

实现并行化的自定义source

  1. 实现ParallelSourceFunction
  2. 或者继承RichParallelSourceFunction
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flink CDC(Change Data Capture)是一种用于捕获和传输数据库变更的技术。在Flink中,可以使用自定义Source来实现Flink CDC。 使用自定义Source的方法是创建一个继承自SourceFunction的类,并重写其中的run()和cancel()方法。在run()方法中,可以调用ctx.collect()将数据返回,实现数据的输出。cancel()方法用于取消任务的执行。 在使用自定义Source时,可以通过env.addSource()方法将自定义SourceFunction添加到Flink的执行环境中。例如,可以使用env.addSource(new CustomGenerator())将自定义SourceFunction添加到执行环境中。 在Flink CDC中,可以使用StartupOptions来指定启动时的操作类型和参数。其中,initial表示第一次启动时读取原表已有的历史数据,之后不断做检查点存储。而在第二次启动时,需要指明检查点文件的具体位置,以实现断点续传。检查点在打包部署后才有用,因为这样才可以指明检查点的具体位置。 输出的数据格式可以根据需求进行定义。例如,可以使用Inserting来表示插入操作,然后使用JSON格式来描述具体的数据内容。例如,输出的数据格式可以是: Inserting ===>>> {"dt":"2023-05-15","name":"刘蓓","id":1,"age":20} Inserting ===>>> {"dt":"2023-05-15","name":"关雨","id":2,"age":20} Inserting ===>>> {"dt":"2023-05-15","name":"张菲","id":3,"age":18} Inserting ===>>> {"dt":"2023-05-16","name":"赵芸","id":4,"age":19} 通过以上方法,可以实现自定义的Flink CDC Source,并根据需求输出相应的数据格式。 #### 引用[.reference_title] - *1* [Flink——自定义Source](https://blog.csdn.net/duxu24/article/details/105547283)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [FlinkCDC自定义反序列化器](https://blog.csdn.net/sis12e/article/details/130020213)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [FlinkCDC之DataStream的反序列自定义](https://blog.csdn.net/m0_48830183/article/details/130718138)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值