从卡夫卡消息中获取卡夫卡记录时间戳

时间:2020-07-16 11:19:15

标签: scala apache-kafka

我想要生产者在kafka主题中插入消息的时间戳。

在卡夫卡消费者方面,我想提取该时间戳。


class Producer {
  def main(args: Array[String]): Unit = {
    writeToKafka("quick-start")
  }
  def writeToKafka(topic: String): Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", "localhost:9094")
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    val producer = new KafkaProducer[String, String](props)
    val record = new ProducerRecord[String, String](topic, "key", "value")
    producer.send(record)
    producer.close()
  }
}



class Consumer {
  def main(args: Array[String]): Unit = {
    consumeFromKafka("quick-start")
  }
  def consumeFromKafka(topic: String) = {
    val props = new Properties()
    props.put("bootstrap.servers", "localhost:9094")
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("auto.offset.reset", "latest")
    props.put("group.id", "consumer-group")
    val consumer: KafkaConsumer[String, String] = new KafkaConsumer[String, String](props)
    consumer.subscribe(util.Arrays.asList(topic))
    while (true) {
      val record = consumer.poll(1000).asScala
      for (data <- record.iterator)
        println(data.value())
    }
  }
}

kafka提供了一种方法吗?否则,我将不得不从生产者向主题发送额外的字段。

1 个答案:

答案 0 :(得分:2)

Kafka提供了自v0.10起的一种方式

从该版本开始,您所有的消息在data.timestamp中都有一个时间戳信息,并且内部的信息种类由代理上的配置“ message.timestamp.type”决定。该值应为CreateTimeLogAppendTime

在此版本之前,通常必须通过修改数据结构来手动实现它。

相关问题