flink消费kafka时获取元数据信息

8 篇文章 0 订阅
7 篇文章 0 订阅

当flink消费kafka时,只需要简单配置就能使用并正常运行

 val env = StreamExecutionEnvironment.getExecutionEnvironment

    val props = new Properties()
    props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.30:9092")
    props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "flink_test")


    val consumer1 = new FlinkKafkaConsumer[String]("mytest", new SimpleStringSchema(), props)
    val stream1 = env.addSource(consumer1)
    stream1.print()

    env.execute("KafkaSourceStreaming")

但是,这里用的是最简单的SimpleStringSchema,所以接收到的数据只是我们所理解的一条消息里的值,其包含的时间戳、offset、topic、partition等元信息都不能正常获取,当需要该部分信息时,可以利用KafkaDeserializationSchema 接口来实现自定义的反序列化逻辑。

object KafkaSourceStreaming {
  def main(args: Array[String]): Unit = {

    val env = StreamExecutionEnvironment.getExecutionEnvironment

    val props = new Properties()
    props.setProperty(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.0.30:9092")
    props.setProperty(ConsumerConfig.GROUP_ID_CONFIG, "flink_test")


    val consumer1 = new FlinkKafkaConsumer[String]("mytest", new SimpleStringSchema(), props)
    val stream1 = env.addSource(consumer1)
    stream1.print()

    val consumer = new FlinkKafkaConsumer("mytest",new CustomKafkaDeserializationSchema(), props)
    val stream = env.addSource(consumer)
    stream.print()

    env.execute("KafkaSourceStreaming")
  }


  /**
    * 获取kafka元数据信息
    */
  class CustomKafkaDeserializationSchema extends KafkaDeserializationSchema[ConsumerRecord[String, String]] {
    override def deserialize(record: ConsumerRecord[Array[Byte], Array[Byte]]): ConsumerRecord[String, String] = {
      val key = if (record.key() == null) null else new String(record.key())
      val value = new String(record.value())
      new ConsumerRecord[String, String](
        record.topic(),
        record.partition(),
        record.offset(),
        record.timestamp(),
        record.timestampType(),
        record.checksum(),
        record.serializedKeySize(),
        record.serializedValueSize(),
        key,
        value,
        record.headers(),
        record.leaderEpoch()
      )
    }

    override def isEndOfStream(nextElement: ConsumerRecord[String, String]): Boolean = false

    override def getProducedType: TypeInformation[ConsumerRecord[String, String]] = {
      TypeInformation.of(new TypeHint[ConsumerRecord[String, String]]() {})
    }
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不加班程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值