1 package de.juplo.kafka;
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.Producer;
5 import org.apache.kafka.clients.producer.KafkaProducer;
6 import org.apache.kafka.clients.producer.ProducerRecord;
7 import org.apache.kafka.common.serialization.StringSerializer;
9 import java.util.Properties;
13 public class SimpleProducer
15 private final String id;
16 private final String topic;
17 private final Producer<String, String> producer;
19 private long produced = 0;
20 private volatile boolean running = true;
21 private volatile boolean done = false;
23 public SimpleProducer(String broker, String topic, String clientId)
25 Properties props = new Properties();
26 props.put("bootstrap.servers", broker);
27 props.put("client.id", clientId); // Nur zur Wiedererkennung
28 props.put("key.serializer", StringSerializer.class.getName());
29 props.put("value.serializer", StringSerializer.class.getName());
33 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={}",