1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.producer.KafkaProducer;
6 import org.apache.kafka.clients.producer.ProducerRecord;
7 import org.springframework.http.HttpStatus;
8 import org.springframework.web.bind.annotation.*;
9 import org.springframework.web.context.request.async.DeferredResult;
11 import javax.annotation.PreDestroy;
12 import java.util.concurrent.ExecutionException;
18 @RequiredArgsConstructor
19 public class RestProducer
21 private final String id;
22 private final String topic;
23 private final Integer partition;
24 private final KafkaProducer<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<>(
44 producer.send(record, (metadata, e) ->
46 long now = System.currentTimeMillis();
51 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
53 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
66 result.setErrorResult(new ProduceFailure(e));
68 "{} - ERROR key={} timestamp={} latency={}ms: {}",
71 metadata == null ? -1 : metadata.timestamp(),
78 long now = System.currentTimeMillis();
80 "{} - Queued message with key={} latency={}ms",
90 @ResponseStatus(HttpStatus.BAD_REQUEST)
91 public ErrorResponse illegalStateException(IllegalStateException e)
93 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());