1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.producer.ProducerRecord;
6 import org.apache.kafka.clients.producer.RecordMetadata;
7 import org.springframework.http.HttpStatus;
8 import org.springframework.kafka.core.KafkaTemplate;
9 import org.springframework.kafka.support.SendResult;
10 import org.springframework.util.concurrent.ListenableFuture;
11 import org.springframework.web.bind.annotation.*;
12 import org.springframework.web.context.request.async.DeferredResult;
18 @RequiredArgsConstructor
19 public class RestGateway
21 private final String id;
22 private final String topic;
23 private final Integer partition;
24 private final KafkaTemplate<String, Integer> kafkaTemplate;
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 Integer value)
34 DeferredResult<ProduceResult> result = new DeferredResult<>();
36 final long time = System.currentTimeMillis();
38 ListenableFuture<SendResult<String, Integer>> future =
39 kafkaTemplate.send(topic, partition, key, value);
41 long now = System.currentTimeMillis();
48 RecordMetadata metadata = sendResult.getRecordMetadata();
49 ProducerRecord<String, Integer> record = sendResult.getProducerRecord();
50 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
52 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
65 result.setErrorResult(new ProduceFailure(e));
67 "{} - ERROR key={} latency={}ms: {}",
76 "{} - Queued message with key={} latency={}ms",
86 @ResponseStatus(HttpStatus.BAD_REQUEST)
87 public ErrorResponse illegalStateException(IllegalStateException e)
89 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());