[英]Apache Kafka Producer - Write to a Topic
如何使用Kafka生產者將其寫入特定分區?
def publishMessage(tsDataPoints: Seq[DataPoint]): Future[Unit] = {
Future {
logger.info(s"Persisting ${tsDataPoints.length} data-points in Kafka topic ${producerConfig.topic}")
val dataPoints = DataPoints("kafkaProducer", tsDataPoints)
val jsonMessage = Json.toJson(dataPoints).toString()
val recordMetaDataF = producer.send(
new ProducerRecord[String, String](producerConfig.topic, jsonMessage)
)
// if we don't make it to Kafka within 3 seconds, we timeout
val recordMetaData = recordMetaDataF.get(3, TimeUnit.SECONDS)
logger.info(
s"persisted ${tsDataPoints.length} data-points to kafka topic: " +
s"${recordMetaData.topic()} partition: ${recordMetaData.partition()} offset: ${recordMetaData.offset()}"
)
()
}
}
上面的代碼將寫入默認分區0,因為我的主題尚未分區!
如何使用特定分區中的使用者讀取? 這是我為消費者准備的:
def readFromKafka = {
val consumerRecords =
consumer.poll(kafkaConsumerPollTimeOut.toMillis).iterator().asScala.toSeq
toTsDataPointSeq(consumerRecords).flatten
}
有什么建議么?
ProducerRecord
的構造函數之一如下
ProducerRecord(String topic, Integer partition, K key, V value)
因此,如果您指定分區(並且該分區存在),則記錄的內容將到達該位置。
如果您希望使用者使用特定分區,則需要調用此方法consumer.assign(List<TopicPartition> partitions)
,您可以在其中指定所需的主題和分區。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.