[英]How spark structured streaming consumers initiated and invoked while reading multi-partitioned kafka topics?
如果kakfa主題具有多個分區,在java中,那么許多使用方實例/線程將在使用方實例化。
如何在火花狀的消費方中處理它? 我沒有找到太多有關相同的信息。 相同的任何樣本,即在某個主題的火花流消費者處調用多個消費者。
周圍的任何設計建議/示例都將非常感謝。
問候,Shyam
如果Kafka有多個分區,則意味着消費者可以通過並行執行某項任務而從中受益。 特別是內部的火花流可通過增加num-executors參數來加快工作速度。 這與Kafka擁有的分區數量有關, 例如,如果您擁有與Spark中的num執行程序相同數量的Kafka分區,則理論上所有執行程序都可以一次讀取所有分區,這顯然增加了系統吞吐量。
只要spark有足夠的資源,Spark流技術始終會從Kafka中的所有可用分區並行讀取數據。 這是Spark的開箱即用,我們不需要為此編寫任何代碼。
例如,如果您的Kafka主題有4個分區,則如果您使用2個具有2個內核的執行程序啟動spark作業,那么您的spark作業將啟動4個任務以從4個Kafka分區並行讀取數據。
如果您需要更多信息,請隨時發表評論。
https://spark.apache.org/docs/2.2.0/streaming-kafka-0-10-integration.html
import java.sql.Timestamp
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.sql.SparkSession
import org.apache.spark.streaming.{Seconds, StreamingContext}
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
import java.time.{LocalDate, LocalDateTime}
import java.util.Calendar
object SparkKafka {
def main(args: Array[String]): Unit = {
val spark = SparkSession
.builder()
.appName("test_app")
.getOrCreate()
val sparkContext = spark.sparkContext
val ssc = new StreamingContext(sparkContext, Seconds(1)) // the polling frequency is 2 seconds, can be modified based on the BM requirements.
///val currentHour = now.get(Calendar.HOUR_OF_DAY)
log.info("Before starting the Stream -->>")
val stream = KafkaUtils.createDirectStream[String, String](ssc, PreferConsistent, Subscribe[String, String]
(Array.apply("Kafka_topic_name"), getKafkaParams()))
.map(record => record.value)
stream.foreachRDD { rdd =>
try {
if (!rdd.isEmpty()) {
log.info("rdd is not empty and saving to -->>"+LocalDate.now.getYear+"/"+LocalDate.now.getMonth+"/"+LocalDate.now.getDayOfMonth+"/"+LocalDateTime.now().getHour)
rdd.saveAsTextFile("hdfs:///<folder to save>") //TODO::: Externalize the HDFS location to Props
LocalDate.now.getMonth
if (null != args && null != args {
0
} && args {
0
}.equals("log")) {
rdd.foreach(x => print("Message read and saved TO S3 bucket----*****--->>" + x))
}
}
} catch {
case t: Throwable =>
t.printStackTrace() // TODO: handle error)
log.error("Exception occured while processing the data exception is {}", t.getCause)
}
}
ssc.start()
log.info("started now-->> " + compat.Platform.currentTime)
ssc.awaitTermination()
}
def getKafkaParams(): Map[String, Object] = {
Map[String, Object]("bootstrap.servers" -> "host:port
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "Group_Name",
// "sasl.kerberos.service.name" -> "kafka",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (true: java.lang.Boolean))
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.