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("metadata.max.age.ms", "1000");
45 props.put("partitioner.class", "org.apache.kafka.clients.producer.RoundRobinPartitioner");
46 props.put("key.serializer", StringSerializer.class.getName());
47 props.put("value.serializer", StringSerializer.class.getName());
49 this.producer = new KafkaProducer<>(props);
59 send(Long.toString(i%10), Long.toString(i));
65 Thread.sleep(throttleMs);
67 catch (InterruptedException e)
69 log.warn("{} - Interrupted while throttling!", e);
74 log.info("{} - Done", id);
78 log.error("{} - Unexpected Exception:", id, e);
85 log.info("{} - Stopped - produced {} messages so far", id, produced);
90 void send(String key, String value)
92 final long time = System.currentTimeMillis();
94 final ProducerRecord<String, String> record = new ProducerRecord<>(
100 producer.send(record, (metadata, e) ->
102 long now = System.currentTimeMillis();
108 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
112 metadata.partition(),
114 metadata.timestamp(),
122 "{} - ERROR key={} timestamp={} latency={}ms: {}",
125 metadata == null ? -1 : metadata.timestamp(),
132 long now = System.currentTimeMillis();
134 "{} - Queued #{} key={} latency={}ms",
142 public synchronized void start()
145 throw new IllegalStateException("Producer instance " + id + " is already running!");
147 log.info("{} - Starting - produced {} messages before", id, produced);
149 executor.submit(this);
152 public synchronized void stop() throws ExecutionException, InterruptedException
155 throw new IllegalStateException("Producer instance " + id + " is not running!");
157 log.info("{} - Stopping...", id);
162 public void destroy() throws ExecutionException, InterruptedException
164 log.info("{} - Destroy!", id);
169 catch (IllegalStateException e)
171 log.info("{} - Was already stopped", id);
175 log.info("{} - Closing the KafkaProducer", id);
177 log.info("{}: Produced {} messages in total, exiting!", id, produced);