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;
12 import java.util.concurrent.Future;
16 public class EndlessProducer implements Runnable
18 private final ExecutorService executor;
19 private final String id;
20 private final String topic;
21 private final String acks;
22 private final int throttleMs;
23 private final KafkaProducer<String, String> producer;
25 private boolean running = false;
27 private long produced = 0;
28 private Future<?> future = null;
30 public EndlessProducer(
31 ExecutorService executor,
32 String bootstrapServer,
38 this.executor = executor;
42 this.throttleMs = throttleMs;
44 Properties props = new Properties();
45 props.put("bootstrap.servers", bootstrapServer);
46 props.put("client.id", clientId);
47 props.put("acks", acks);
48 props.put("partitioner.class", "org.apache.kafka.clients.producer.RoundRobinPartitioner");
49 props.put("key.serializer", StringSerializer.class.getName());
50 props.put("value.serializer", StringSerializer.class.getName());
52 this.producer = new KafkaProducer<>(props);
62 final long time = System.currentTimeMillis();
64 final ProducerRecord<String, String> record = new ProducerRecord<>(
66 Long.toString(i % 10), // Key
67 Long.toString(i) // Value
70 producer.send(record, (metadata, e) ->
72 long now = System.currentTimeMillis();
78 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
92 "{} - ERROR key={} timestamp={} latency={}ms: {}",
95 metadata == null ? -1 : metadata.timestamp(),
102 long now = System.currentTimeMillis();
104 "{} - Queued #{} key={} latency={}ms",
115 Thread.sleep(throttleMs);
117 catch (InterruptedException e)
119 log.warn("{} - Interrupted while throttling!", e);
124 log.info("{} - Done", id);
132 public synchronized void start()
135 throw new IllegalStateException("Producer instance " + id + " is already running!");
137 log.info("{} - Starting - produced {} messages before", id, produced);
139 future = executor.submit(this);
142 public synchronized void stop() throws ExecutionException, InterruptedException
145 throw new IllegalStateException("Producer instance " + id + " is not running!");
147 log.info("{} - Stopping...", id);
150 log.info("{} - Stopped - produced {} messages so far", id, produced);
154 public void destroy() throws ExecutionException, InterruptedException
156 log.info("{} - Destroy!", id);
161 catch (IllegalStateException e)
163 log.info("{} - Was already stopped", id);
167 log.info("{} - Closing the KafkaProducer", id);
169 log.info("{}: Produced {} messages in total, exiting!", id, produced);