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()
      
    }
相关推荐
Hello.Reader3 小时前
Flink Checkpoint 通用调优方案三种画像 + 配置模板 + 容量估算 + 巡检脚本 + 告警阈值
大数据·flink
Hy行者勇哥5 小时前
公司全场景运营中 PPT 的类型、功能与作用详解
大数据·人工智能
liliangcsdn6 小时前
如何基于ElasticsearchRetriever构建RAG系统
大数据·elasticsearch·langchain
乐迪信息6 小时前
乐迪信息:基于AI算法的煤矿作业人员安全规范智能监测与预警系统
大数据·人工智能·算法·安全·视觉检测·推荐算法
极验6 小时前
iPhone17实体卡槽消失?eSIM 普及下的安全挑战与应对
大数据·运维·安全
B站_计算机毕业设计之家7 小时前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
The Sheep 20237 小时前
WPF自定义路由事件
大数据·hadoop·wpf
SelectDB技术团队8 小时前
Apache Doris 内部数据裁剪与过滤机制的实现原理 | Deep Dive
大数据·数据库·apache·数据库系统·数据裁剪
WLJT1231231238 小时前
科技赋能塞上农业:宁夏从黄土地到绿硅谷的蝶变
大数据·人工智能·科技