Df发送到kafka

该代码示例展示了如何在Scala中配置一个KafkaProducer,使用SSL安全连接,并将SparkSQLDataFrame的数据写入Kafka主题。数据被Avro序列化,并通过指定的SchemaRegistry进行处理。
摘要由CSDN通过智能技术生成

import java.util.Properties

 

import io.confluent.kafka.serializers.{AbstractKafkaAvroSerDeConfig, KafkaAvroSerializer}

import org.apache.avro.Schema

import org.apache.kafka.clients.CommonClientConfigs

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import org.apache.kafka.common.config.SslConfigs

import org.apache.spark.sql.DataFrame

 

object KafkaProducerDF {

 

  val kafkaParams: Map[String, Object] = Map(

    CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG -> "localhost:9092",

    CommonClientConfigs.SECURITY_PROTOCOL_CONFIG -> "SSL",

    SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG -> "/path/to/truststore.jks",

    SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG -> "truststore-password",

    SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG -> "/path/to/keystore.jks",

    SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG -> "keystore-password",

    SslConfigs.SSL_KEY_PASSWORD_CONFIG -> "key-password",

    "key.serializer" -> "org.apache.kafka.common.serialization.StringSerializer",

    "value.serializer" -> classOf[KafkaAvroSerializer],

    AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG -> "https://schema-registry-url:8081",

    AbstractKafkaAvroSerDeConfig.VALUE_SUBJECT_NAME_STRATEGY -> "io.confluent.kafka.serializers.subject.TopicNameStrategy"

  )

 

  def writeToKafka(df: DataFrame, topic: String, schema: String): Unit = {

    df.foreachPartition { partition =>

      val props = new Properties()

      props.putAll(kafkaParams.asJava)

 

      val producer = new KafkaProducer[String, AnyRef](props)

 

      val avroSchema = new Schema.Parser().parse(schema)

 

      partition.foreach { row =>

        val key = row.getAs[String]("key")

        val value = AvroUtils.toAvro(row, avroSchema)

 

        val record = new ProducerRecord[String, AnyRef](topic, key, value)

        producer.send(record)

      }

 

      producer.flush()

      producer.close()

    }

  }

}

 

object AvroUtils {

  def toAvro(row: Row, schema: Schema): AnyRef = {

    val builder = new GenericRecordBuilder(schema)

    for (i <- 0 until row.length) {

      builder.set(schema.getFields.get(i).name(), row.get(i))

    }

    builder.build()

  }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值