我如何使用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
}
有什么建议吗?
答案 0 :(得分:1)
ProducerRecord
的其中一个构造函数如下
ProducerRecord(String topic, Integer partition, K key, V value)
因此,如果您指定分区(并且分区存在),您将记录该位置。
如果您希望消费者使用特定分区,则需要调用此方法consumer.assign(List<TopicPartition> partitions)
,您可以指定哪个是您想要的主题和分区。