Monday, August 3, 2020

Scala Kafka Producer

In this post we will learn how to send messages to Kafka using Scala.

Add the following library dependency.

libraryDependencies += "org.apache.kafka" %% "kafka" % "2.1.0"

Following is the scala code to send (produce) messages to Kafka.

import java.util.Properties
import org.apache.kafka.clients.producer._
object SendMessagesToKafka {
  def main(args: Array[String]): Unit = {
    sendMessagesToKafka("Topic1")
  }
  def sendMessagesToKafka(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()
  }
}

That's it!
Cheers!

No comments:

Post a Comment