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()
      
    }
相关推荐
悻运15 分钟前
Spark论述及其作用
大数据·分布式·spark
szxinmai主板定制专家32 分钟前
国产RK3568+FPGA以 ‌“实时控制+高精度采集+灵活扩展”‌ 为核心的解决方案
大数据·运维·网络·人工智能·fpga开发·机器人
细心的莽夫2 小时前
Elasticsearch复习笔记
java·大数据·spring boot·笔记·后端·elasticsearch·docker
痕5173 小时前
spark和Hadoop之间的对比和联系
大数据·hadoop·spark
CXH7283 小时前
hadoop分布式部署
大数据·hadoop·分布式
码农周4 小时前
Elasticsearch 报错 Limit of total fields [1000] has been exceeded
大数据·elasticsearch
晴天彩虹雨4 小时前
实时数仓体系概览与架构演进
数据仓库·clickhouse·架构·flink·kafka
1momomo汉堡包4 小时前
spark和hadoop之间的对比和联系
大数据·hadoop·spark
Elastic 中国社区官方博客5 小时前
Elasticsearch 堆内存使用情况和 JVM 垃圾回收
大数据·jvm·数据库·elasticsearch·搜索引擎·全文检索
博弈美业系统Java源码5 小时前
连锁美业管理系统「数据分析」的重要作用分析︳博弈美业系统疗愈系统分享
java·大数据·前端·后端·创业创新