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());
31 producer = new KafkaProducer<>(props);
45 send(Long.toString(i%10), Long.toString(i));
49 catch (InterruptedException e) {}
52 log.info("{}: Closing the KafkaProducer", id);
54 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 String broker = ":9092";
115 String topic = "test";
116 String clientId = "DEV";
128 SimpleProducer instance = new SimpleProducer(broker, topic, clientId);
130 Runtime.getRuntime().addShutdownHook(new Thread(() ->
132 instance.running = false;
133 while (!instance.done)
135 log.info("Waiting for main-thread...");
140 catch (InterruptedException e) {}
142 log.info("Shutdown completed.");
146 "Running SimpleProducer: broker={}, topic={}, client-id={}",