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 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);
82 void send(String key, String value)
84 final long time = System.currentTimeMillis();
86 final ProducerRecord<String, String> record = new ProducerRecord<>(
92 producer.send(record, (metadata, e) ->
94 long now = System.currentTimeMillis();
100 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
104 metadata.partition(),
106 metadata.timestamp(),
114 "{} - ERROR key={} timestamp={} latency={}ms: {}",
117 metadata == null ? -1 : metadata.timestamp(),
124 long now = System.currentTimeMillis();
126 "{} - Queued #{} key={} latency={}ms",
134 public synchronized void start()
137 throw new IllegalStateException("Producer instance " + id + " is already running!");
139 log.info("{} - Starting - produced {} messages before", id, produced);
141 future = executor.submit(this);
144 public synchronized void stop() throws ExecutionException, InterruptedException
147 throw new IllegalStateException("Producer instance " + id + " is not running!");
149 log.info("{} - Stopping...", id);
152 log.info("{} - Stopped - produced {} messages so far", id, produced);
156 public void destroy() throws ExecutionException, InterruptedException
158 log.info("{} - Destroy!", id);
163 catch (IllegalStateException e)
165 log.info("{} - Was already stopped", id);
169 log.info("{} - Closing the KafkaProducer", id);
171 log.info("{}: Produced {} messages in total, exiting!", id, produced);