1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.producer.Producer;
6 import org.apache.kafka.clients.producer.KafkaProducer;
7 import org.apache.kafka.clients.producer.ProducerRecord;
8 import org.springframework.http.HttpStatus;
9 import org.springframework.web.bind.annotation.*;
10 import org.springframework.web.context.request.async.DeferredResult;
12 import java.math.BigInteger;
18 @RequiredArgsConstructor
19 public class RestProducer
21 private final String id;
22 private final String topic;
23 private final Integer partition;
24 private final Producer<String, String> producer;
26 private long produced = 0;
28 @PostMapping(path = "{key}")
29 public DeferredResult<ProduceResult> send(
30 @PathVariable String key,
31 @RequestHeader(name = "X-id", required = false) Long correlationId,
32 @RequestBody String value)
34 DeferredResult<ProduceResult> result = new DeferredResult<>();
36 final long time = System.currentTimeMillis();
38 final ProducerRecord<String, String> record = new ProducerRecord<>(
40 partition, // Partition
45 record.headers().add("source", id.getBytes());
46 if (correlationId != null)
48 record.headers().add("id", BigInteger.valueOf(correlationId).toByteArray());
51 producer.send(record, (metadata, e) ->
53 long now = System.currentTimeMillis();
58 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
60 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
73 result.setErrorResult(new ProduceFailure(e));
75 "{} - ERROR key={} timestamp={} latency={}ms: {}",
78 metadata == null ? -1 : metadata.timestamp(),
85 long now = System.currentTimeMillis();
87 "{} - Queued message with key={} latency={}ms",
97 @ResponseStatus(HttpStatus.BAD_REQUEST)
98 public ErrorResponse illegalStateException(IllegalStateException e)
100 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());