Flink自定义source(单并行度和多并行度)

本文介绍了Apache Flink中的数据源(Source)概念,包括预定义的Source如基于文件、Socket、集合和Kafka的Source,以及如何自定义单并行度和多并行度Source。通过实现SourceFunction或ParallelSourceFunction接口,开发者可以创建自己的数据源,并调整并行度以适应不同的处理需求。示例代码展示了如何创建和消费这些Source。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


DataStream是Flink的较低级API,用于进行数据的实时处理任务,可以将该编程模型分为Source、Transformation、Sink三个部分,如下图所示。本文来介绍常用的并行度Source和多并行度Source。
在这里插入图片描述

1.Source简介

source是程序的数据源输入,你可以通过StreamExecutionEnvironment.addSource(sourceFunction)
来为你的程序添加一个source。
在这里插入图片描述
flink提供了大量的已经实现好的source方法,也可以自定义source:

  1. 通过实现sourceFunction接口来自定义无并行度的source
  2. 通过实现ParallelSourceFunction 接口or 继承RichParallelSourceFunction 来自定义有并行度的
    source

大多数情况下,我们使用自带的source即可。

2. Flink预定义的Source

flink提供了大量的已经实现好的source,常见的有:Flink source

  • 基于文件的Source
  • 基于Socket的Source
  • 基于集合的Source
  • 基于Kafka的Source

3. 自定义单并行度Source

除了flink本身提供的source之外,我们也可以自定义source。可以通过实现sourceFunction接口来自定义无并行度的source。

示例如下:

(1)自定义Source

import org.apache.flink.streaming.api.functions.source.SourceFunction;
//功能:每秒产生一条数据
public class MyNoParallelSource implements SourceFunction<Long> {
    private long number = 1L;
    private boolean isRunning = true;
    @Override
    public void run(SourceContext<Long> sct) throws Exception {
        while (isRunning){
            sct.collect(number);
            number++;
            //每秒生成一条数据
            Thread.sleep(1000);
        }
    }
    @Override
    public void cancel() {
        isRunning=false;
    }
}

(2)定义Consume,消费Source的数据,并打印输出

import org.apache.flink.api.common.functions.FilterFunction;
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;
//功能:打印输出偶数
public class MyNoParallelConsumer {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env= StreamExecutionEnvironment.getExecutionEnvironment();
        //默认并行度为1
        DataStreamSource<Long> numberStream = env.addSource(new MyNoParallelSource());
        DataStream<Long> dataStream = numberStream.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("接受到了数据:"+value);
                return value;
            }
        });
        DataStream<Long> filterDataStream = dataStream.filter(new FilterFunction<Long>() {
            @Override
            public boolean filter(Long value) throws Exception {
                return value % 2 == 0; //过滤偶数
            }
        });
        filterDataStream.print().setParallelism(1);
        env.execute();
    }
}

4. 自定义多并行度Source

通过实现ParallelSourceFunction 接口or 继承RichParallelSourceFunction 来自定义有并行度的
source。

(1)自定义多并行度Source

import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
//功能:自定义支持并行度的数据源
public class MyParallelSource implements ParallelSourceFunction<Long> {
    private long number = 1L;
    private boolean isRunning = true;
    @Override
    public void run(SourceContext<Long> sct) throws Exception {
        while (isRunning){
            sct.collect(number);
            number++;
            //每秒生成一条数据
            Thread.sleep(1000);
        }
    }
    @Override
    public void cancel() {
        isRunning=false;
    }
}

(2)定义Consume,消费多并行度Source的数据,并打印输出

import org.apache.flink.api.common.functions.FilterFunction;
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;
//功能:消费多并行度Source的数据,并打印输出偶数
public class MyParallelConsumer {
    public static void main(String[] args) throws Exception {
        //创建执行环境
        StreamExecutionEnvironment env= StreamExecutionEnvironment.getExecutionEnvironment();
        //默认并行度为cpu core数,我这里为4
        DataStreamSource<Long> numberStream = env.addSource(new MyParallelSource());
        DataStream<Long> dataStream = numberStream.map(new MapFunction<Long, Long>() {
            @Override
            public Long map(Long value) throws Exception {
                System.out.println("接受到了数据:"+value);
                return value;
            }
        });
        DataStream<Long> filterDataStream = dataStream.filter(new FilterFunction<Long>() {
            @Override
            public boolean filter(Long value) throws Exception {
                return value % 2 == 0;
            }
        });
        filterDataStream.print().setParallelism(1);
        env.execute();
    }
}

可以看到,如果不设置并行度,Source默认并行度为cpu core数,我这里是4。

### 如何在 Flink SQL 中为 Kafka Source 设置自定义并行度 在 Apache Flink 的流处理环境中,可以通过种方式配置作业的不同组件的并行度。对于 Kafka Source,在 Flink SQL 中设置其并行度主要依赖于 `CREATE TABLE` 语句中的属性以及启动环境时指定参数。 #### 方法一:通过 CREATE TABLE 语句设定 可以在创建表的时候利用 WITH 子句来指明 source 并行度: ```sql CREATE TABLE my_kafka_table ( ... ) WITH ( 'connector' = 'kafka', 'topic' = 'your_topic_name', 'properties.bootstrap.servers' = 'localhost:9092', 'format' = 'json', -- 数据格式化器 'scan.startup.mode' = 'earliest-offset', 'parallelism' = '4' -- 自定义source并行度 ); ``` 此方法直接将并行度作为一个表级别的配置项传递给底层 Connector 实现[^3]。 #### 方法二:通过 TableEnvironment 设置全局或特定操作符的并行度 另一种更为灵活的方式是在初始化 TableEnvironment 后调整整个应用程序或者个算子的默认并行度: ```python from pyflink.dataset import ExecutionEnvironment from pyflink.table import BatchTableEnvironment, StreamTableEnvironment, EnvironmentSettings env_settings = EnvironmentSettings.in_streaming_mode() table_env = StreamTableEnvironment.create(env=ExecutionEnvironment.get_execution_environment(), settings=env_settings) # 设定全局并行度 table_env.get_config().set_parallelism(8) # 或者针对某个查询独设定并行度 result = table_env.execute_sql("...").get_job_client().get_job_status_result().get_job_parameters().set("pipeline.parallelism", "6") ``` 值得注意的是,上述 Python 示例展示了如何改变整体程序或是具体任务链路内的并行程度;而对于 Kafka Source 来说,最推荐的做法还是采用第一种方案即在 DDL 定义阶段就明确指出所需并行数[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值