Sample #Kafka producer with #Groovy

Here is a brief example of Kafka producer client written in Groovy:

import org.apache.kafka.clients.producer.Callback
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.clients.producer.RecordMetadata
@Grab(group = "org.apache.kafka", module = "kafka-clients", version = "")
@Grab(group = 'ch.qos.logback', module = 'logback-classic', version = '1.1.2')
Properties props = new Properties()
props.put('zk.connect', '')
props.put('bootstrap.servers', ',,')
props.put('key.serializer', 'org.apache.kafka.common.serialization.StringSerializer')
props.put('value.serializer', 'org.apache.kafka.common.serialization.StringSerializer')
def producer = new KafkaProducer(props)
def messageSender = { String topic, String message ->
    String key = new Random().nextLong()
    String compoundMessage = "key: $key, message: $message"
            new ProducerRecord<String, String>(topic, key, compoundMessage),
            { RecordMetadata metadata, Exception e ->
                println "The offset of the record we just sent is: ${metadata.offset()}"
            } as Callback
args.each { arg ->
    println "sending message $arg"
    messageSender('simple.topic', arg)

In order to run it use:

groovy producer.groovy hello from Groovy client

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.