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 int throttleMs;
22 private final KafkaProducer<String, String> producer;
24 private boolean running = false;
26 private long produced = 0;
27 private Future<?> future = null;
29 public EndlessProducer(
30 ExecutorService executor,
31 String bootstrapServer,
37 this.executor = executor;
40 this.throttleMs = throttleMs;
42 Properties props = new Properties();
43 props.put("bootstrap.servers", bootstrapServer);
44 props.put("client.id", clientId);
45 props.put("acks", acks);
46 props.put("key.serializer", StringSerializer.class.getName());
47 props.put("value.serializer", StringSerializer.class.getName());
49 this.producer = new KafkaProducer<>(props);
59 final long time = System.currentTimeMillis();
61 final ProducerRecord<String, String> record = new ProducerRecord<>(
63 Long.toString(i % 10), // Key
64 Long.toString(i) // Value
67 producer.send(record, (metadata, e) ->
69 long now = System.currentTimeMillis();
75 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
89 "{} - ERROR key={} timestamp={} latency={}ms: {}",
92 metadata == null ? -1 : metadata.timestamp(),
99 long now = System.currentTimeMillis();
101 "{} - Queued #{} key={} latency={}ms",
112 Thread.sleep(throttleMs);
114 catch (InterruptedException e)
116 log.warn("{} - Interrupted while throttling!", e);
121 log.info("{} - Done", id);
129 public synchronized void start()
132 throw new IllegalStateException("Producer instance " + id + " is already running!");
134 log.info("{} - Starting - produced {} messages before", id, produced);
136 future = executor.submit(this);
139 public synchronized void stop() throws ExecutionException, InterruptedException
142 throw new IllegalStateException("Producer instance " + id + " is not running!");
144 log.info("{} - Stopping...", id);
147 log.info("{} - Stopped - produced {} messages so far", id, produced);
151 public void destroy() throws ExecutionException, InterruptedException
153 log.info("{} - Destroy!", id);
158 catch (IllegalStateException e)
160 log.info("{} - Was already stopped", id);
164 log.info("{} - Closing the KafkaProducer", id);
166 log.info("{}: Produced {} messages in total, exiting!", id, produced);