package de.juplo.kafka;
import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
-import org.apache.kafka.common.serialization.StringSerializer;
+import org.apache.kafka.clients.producer.RecordMetadata;
+import org.springframework.kafka.core.KafkaTemplate;
+import org.springframework.kafka.support.SendResult;
+import org.springframework.util.concurrent.ListenableFuture;
import javax.annotation.PreDestroy;
-import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
{
private final ExecutorService executor;
private final String id;
- private final String topic;
private final int throttleMs;
- private final KafkaProducer<String, String> producer;
+ private final KafkaTemplate<String, String> kafkaTemplate;
private boolean running = false;
private long i = 0;
public EndlessProducer(
ExecutorService executor,
- String bootstrapServer,
String clientId,
- String topic,
- String acks,
- int throttleMs)
+ int throttleMs,
+ KafkaTemplate<String, String> kafkaTemplate)
{
this.executor = executor;
this.id = clientId;
- this.topic = topic;
this.throttleMs = throttleMs;
-
- Properties props = new Properties();
- props.put("bootstrap.servers", bootstrapServer);
- props.put("client.id", clientId);
- props.put("acks", acks);
- props.put("key.serializer", StringSerializer.class.getName());
- props.put("value.serializer", StringSerializer.class.getName());
-
- this.producer = new KafkaProducer<>(props);
+ this.kafkaTemplate = kafkaTemplate;
}
@Override
{
final long time = System.currentTimeMillis();
- final ProducerRecord<String, String> record = new ProducerRecord<>(
- topic, // Topic
- key, // Key
- value // Value
- );
-
- producer.send(record, (metadata, e) ->
- {
- long now = System.currentTimeMillis();
- if (e == null)
+ ListenableFuture<SendResult<String, String>> listenableFuture = kafkaTemplate.sendDefault(key, value);
+ listenableFuture.addCallback(
+ result ->
{
+ long now = System.currentTimeMillis();
+ RecordMetadata metadata = result.getRecordMetadata();
+ ProducerRecord<String, String> record = result.getProducerRecord();
+
// HANDLE SUCCESS
produced++;
log.debug(
metadata.timestamp(),
now - time
);
- }
- else
+ },
+ e ->
{
+ long now = System.currentTimeMillis();
+
// HANDLE ERROR
log.error(
- "{} - ERROR key={} timestamp={} latency={}ms: {}",
+ "{} - ERROR key={} latency={}ms: {}",
id,
- record.key(),
- metadata == null ? -1 : metadata.timestamp(),
+ key,
now - time,
e.toString()
);
- }
- });
+ });
long now = System.currentTimeMillis();
log.trace(
"{} - Queued #{} key={} latency={}ms",
id,
value,
- record.key(),
+ key,
now - time
);
}
}
finally
{
- log.info("{} - Closing the KafkaProducer", id);
- producer.close();
log.info("{}: Produced {} messages in total, exiting!", id, produced);
}
}