package de.juplo.kafka;
import lombok.extern.slf4j.Slf4j;
-import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.springframework.http.HttpStatus;
import org.springframework.kafka.core.KafkaTemplate;
@RequestBody String value)
{
key = key.trim();
- final ProducerRecord<String, Object> record = new ProducerRecord<>(
- topic, // Topic
- key, // Key
- new ClientMessage(key, value) // Value
- );
-
- return send(record);
+ return send(key, new ClientMessage(key, value));
}
@PutMapping(path = "{key}")
public DeferredResult<ProduceResult> message(@PathVariable String key)
{
key = key.trim();
- final ProducerRecord<String, Object> record = new ProducerRecord<>(
- topic, // Topic
- key, // Key
- new FooMessage(key, System.currentTimeMillis()) // Value
- );
-
- return send(record);
+ return send(key, new FooMessage(key, System.currentTimeMillis()));
}
@PostMapping(path = "/")
@RequestBody String name)
{
name = name.trim();
- final ProducerRecord<String, Object> record = new ProducerRecord<>(
- topic, // Topic
- name, // Key
- new Greeting(name) // Value
- );
-
- return send(record);
+ return send(name, new Greeting(name));
}
- private DeferredResult<ProduceResult> send(ProducerRecord<String, Object> record)
+ private DeferredResult<ProduceResult> send(String key, Object value)
{
DeferredResult<ProduceResult> result = new DeferredResult<>();
final long time = System.currentTimeMillis();
- kafkaTemplate.send(record).addCallback(
+ kafkaTemplate.send(topic, key, value).addCallback(
(sendResult) ->
{
long now = System.currentTimeMillis();
log.debug(
"{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
id,
- record.key(),
- record.value(),
+ key,
+ value,
metadata.partition(),
metadata.offset(),
metadata.timestamp(),
log.error(
"{} - ERROR key={} timestamp=-1 latency={}ms: {}",
id,
- record.key(),
+ key,
now - time,
e.toString()
);
log.trace(
"{} - Queued key={} latency={}ms",
id,
- record.key(),
+ key,
now - time
);