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()
      
    }
相关推荐
西格电力科技27 分钟前
面向工业用户的绿电直连架构适配技术:高可靠与高弹性的双重设计
大数据·服务器·人工智能·架构·能源
beijingliushao2 小时前
105-Spark之Standalone HA环境搭建过程
大数据·spark
五阿哥永琪2 小时前
Git 开发常用命令速查手册
大数据·git·elasticsearch
数字会议深科技2 小时前
深科技 | 高端会议室效率升级指南:无纸化会议系统的演进与价值
大数据·人工智能·会议系统·无纸化·会议系统品牌·综合型系统集成商·会议室
容智信息3 小时前
容智Report Agent智能体驱动财务自动化,从核算迈向价值创造
大数据·运维·人工智能·自然语言处理·自动化·政务
神算大模型APi--天枢6463 小时前
全栈自主可控:国产算力平台重塑大模型后端开发与部署生态
大数据·前端·人工智能·架构·硬件架构
每日学点SEO4 小时前
「网站新页面冲进前10名成功率下降69%」:2025 年SEO竞争格局分析
大数据·数据库·人工智能·搜索引擎·chatgpt
写代码的【黑咖啡】5 小时前
大数据建模中的模型
大数据
驾数者5 小时前
Flink SQL模式识别:MATCH_RECOGNIZE复杂事件处理
数据库·sql·flink
ljh5746491196 小时前
大数据geo是什么意思
大数据·人工智能