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;
12 public class SimpleProducer
14 private final String id;
15 private final String topic;
16 private final KafkaProducer<String, String> producer;
18 private long produced = 0;
19 private volatile boolean running = true;
20 private volatile boolean done = false;
22 public SimpleProducer(String broker, String topic, String clientId)
24 Properties props = new Properties();
25 props.put("bootstrap.servers", broker);
26 props.put("client.id", clientId); // Nur zur Wiedererkennung
27 props.put("key.serializer", StringSerializer.class.getName());
28 props.put("value.serializer", StringSerializer.class.getName());
30 producer = new KafkaProducer<>(props);
44 send(Long.toString(i%10), Long.toString(i));
48 catch (InterruptedException e) {}
51 log.info("{}: Closing the KafkaProducer", id);
53 log.info("{}: Produced {} messages in total, exiting!", id, produced);
58 void send(String key, String value)
60 final long time = System.currentTimeMillis();
62 final ProducerRecord<String, String> record = new ProducerRecord<>(
68 producer.send(record, (metadata, e) ->
70 long now = System.currentTimeMillis();
76 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
90 "{} - ERROR key={} timestamp={} latency={}ms: {}",
93 metadata == null ? -1 : metadata.timestamp(),
100 long now = System.currentTimeMillis();
102 "{} - Queued #{} key={} latency={}ms",
111 public static void main(String[] args) throws Exception
113 String broker = ":9092";
114 String topic = "test";
115 String clientId = "DEV";
127 SimpleProducer instance = new SimpleProducer(broker, topic, clientId);
129 Runtime.getRuntime().addShutdownHook(new Thread(() ->
131 instance.running = false;
132 while (!instance.done)
134 log.info("Waiting for main-thread...");
139 catch (InterruptedException e) {}
141 log.info("Shutdown completed.");
145 "Running SimpleProducer: broker={}, topic={}, client-id={}",