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 javax.annotation.PreDestroy;
9 import java.util.Properties;
10 import java.util.concurrent.ExecutionException;
11 import java.util.concurrent.ExecutorService;
15 public class EndlessProducer implements Runnable
17 private final ExecutorService executor;
18 private final String id;
19 private final String topic;
20 private final int throttleMs;
21 private final KafkaProducer<String, String> producer;
23 private boolean running = false;
25 private long produced = 0;
27 public EndlessProducer(
28 ExecutorService executor,
29 String bootstrapServer,
35 this.executor = executor;
38 this.throttleMs = throttleMs;
40 Properties props = new Properties();
41 props.put("bootstrap.servers", bootstrapServer);
42 props.put("client.id", clientId);
43 props.put("acks", acks);
44 props.put("key.serializer", StringSerializer.class.getName());
45 props.put("value.serializer", StringSerializer.class.getName());
47 this.producer = new KafkaProducer<>(props);
57 send(Long.toString(i%10), Long.toString(i));
63 Thread.sleep(throttleMs);
65 catch (InterruptedException e)
67 log.warn("{} - Interrupted while throttling!", e);
72 log.info("{} - Done", id);
76 log.error("{} - Unexpected Exception:", id, e);
83 log.info("{} - Stopped - produced {} messages so far", id, produced);
88 void send(String key, String value)
90 final long time = System.currentTimeMillis();
92 final ProducerRecord<String, String> record = new ProducerRecord<>(
98 producer.send(record, (metadata, e) ->
100 long now = System.currentTimeMillis();
106 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
110 metadata.partition(),
112 metadata.timestamp(),
120 "{} - ERROR key={} timestamp={} latency={}ms: {}",
123 metadata == null ? -1 : metadata.timestamp(),
130 long now = System.currentTimeMillis();
132 "{} - Queued #{} key={} latency={}ms",
140 public synchronized void start()
143 throw new IllegalStateException("Producer instance " + id + " is already running!");
145 log.info("{} - Starting - produced {} messages before", id, produced);
147 executor.submit(this);
150 public synchronized void stop() throws ExecutionException, InterruptedException
153 throw new IllegalStateException("Producer instance " + id + " is not running!");
155 log.info("{} - Stopping...", id);
160 public void destroy() throws ExecutionException, InterruptedException
162 log.info("{} - Destroy!", id);
167 catch (IllegalStateException e)
169 log.info("{} - Was already stopped", id);
173 log.info("{} - Closing the KafkaProducer", id);
175 log.info("{}: Produced {} messages in total, exiting!", id, produced);