1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.KafkaProducer;
5 import org.apache.kafka.clients.producer.ProducerRecord;
6 import org.apache.kafka.common.serialization.StringSerializer;
8 import java.util.Properties;
9 import java.util.concurrent.ExecutorService;
10 import java.util.concurrent.Future;
14 public class SimpleProducer
16 private final String id;
17 private final String topic;
18 private final KafkaProducer<String, String> producer;
20 private long produced = 0;
22 public SimpleProducer(String clientId, String topic)
25 Properties props = new Properties();
26 props.put("bootstrap.servers", "localhost:9092");
27 props.put("key.serializer", StringSerializer.class.getName());
28 props.put("value.serializer", StringSerializer.class.getName());
30 KafkaProducer<String, String> producer = new KafkaProducer<>(props);
35 this.producer = producer;
46 send(Long.toString(i%10), Long.toString(i));
49 log.info("{} - Done", id);
53 log.info("{}: Closing the KafkaProducer", id);
55 log.info("{}: Produced {} messages in total, exiting!", id, produced);
59 void send(String key, String value)
61 final long time = System.currentTimeMillis();
63 final ProducerRecord<String, String> record = new ProducerRecord<>(
69 producer.send(record, (metadata, e) ->
71 long now = System.currentTimeMillis();
77 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
91 "{} - ERROR key={} timestamp={} latency={}ms: {}",
94 metadata == null ? -1 : metadata.timestamp(),
101 long now = System.currentTimeMillis();
103 "{} - Queued #{} key={} latency={}ms",
112 public static void main(String[] args) throws Exception
114 SimpleProducer producer = new SimpleProducer("P", "test");