3. 自定义datasource

一、自定义DataSource

​ 自定义DataSource有两大类:单线程的DataSource和多线程的DataSource

  • 单线程:继承 SourceFunction

  • 多线程:继承 ParallelSourceFunction,继承 RichParallelSourceFunction(可以有其他的很多操作)

    scala 复制代码
    import org.apache.flink.configuration.Configuration
    import org.apache.flink.streaming.api.functions.source.{ParallelSourceFunction, RichParallelSourceFunction, SourceFunction}
    
    //1. 单线程
    class MyNoParallelSource1 extends SourceFunction[Long] {
    
      var count = 1L;
      var isRunning = true
    
      override def run(ctx: SourceFunction.SourceContext[Long]): Unit = {
        while(isRunning) {
          ctx.collect(count)
          count += 1
          Thread.sleep(1000)
        }
      }
    
      override def cancel(): Unit = {
        isRunning = false
      }
    }
    
    //2. 多线程
    class MyNoParallelSource2 extends ParallelSourceFunction[Long] {
    
      var count = 1L
      var isRunning = true
    
      override def run(ctx: SourceFunction.SourceContext[Long]): Unit = {
        while(isRunning) {
          ctx.collect(count)
          count += 1
          Thread.sleep(1000)
        }
      }
    
      override def cancel(): Unit = {
        isRunning = false
      }
    }
    
    /**3. 多线程使用RichFunction的方式
     * 提供了open和close方法,可以用于打开和释放资源
     */
    class MyNoParallelSource3 extends RichParallelSourceFunction[Long] {
    
      var count = 1
      var isRunning = true
    
      override def run(ctx: SourceFunction.SourceContext[Long]): Unit = {
        while (isRunning) {
          ctx.collect(count)
          count += 1
          Thread.sleep(1000)
        }
      }
    
      override def cancel(): Unit = {
        isRunning = false
      }
    
      override def open(parameters: Configuration): Unit = super.open(parameters)
    
      override def close(): Unit = super.close()
      
    }
相关推荐
Data-Miner1 小时前
精品PPT | 某制造集团灯塔工厂解决方案
大数据·人工智能·制造
小湘西1 小时前
Elasticsearch 的一些默认配置上下限
java·大数据·elasticsearch
`林中水滴`2 小时前
SeaTunnel vs Flume
大数据·flume
边缘计算社区2 小时前
第12届全球边缘计算大会-精彩瞬间
大数据·人工智能·边缘计算
Zoey的笔记本3 小时前
告别“人机混战”:如何用智能管控实现安全高效协同
大数据·人工智能
奥利文儿3 小时前
【虚拟机】Ubuntu24安装Miniconda3全记录:避坑指南与实践
大数据·数据仓库·人工智能·数据库开发·etl·虚拟机·etl工程师
2401_835302483 小时前
精准测试赋能高端制造!陶瓷基板介电常数测试的核心价值
大数据·人工智能·制造
飞Link3 小时前
【Hadoop】Linux(CentOS7)下安装Hadoop集群
大数据·linux·hadoop·分布式
Dxy12393102164 小时前
Elasticsearch 8如何做好标题搜索
大数据·elasticsearch
飞Link4 小时前
【Hive】Linux(CentOS7)下安装Hive教程
大数据·linux·数据仓库·hive·hadoop