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 Integer partition;
23 private final KafkaTemplate<String, Integer> kafkaTemplate;
25 private long produced = 0;
27 @PostMapping(path = "{key}")
28 public DeferredResult<ProduceResult> send(
29 @PathVariable String key,
30 @RequestHeader(name = "X-id", required = false) Long correlationId,
31 @RequestBody Integer value)
33 DeferredResult<ProduceResult> result = new DeferredResult<>();
35 final long time = System.currentTimeMillis();
37 ListenableFuture<SendResult<String, Integer>> future =
38 kafkaTemplate.send(null, partition, key, value);
40 long now = System.currentTimeMillis();
47 RecordMetadata metadata = sendResult.getRecordMetadata();
48 ProducerRecord<String, Integer> record = sendResult.getProducerRecord();
49 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
51 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
64 result.setErrorResult(new ProduceFailure(e));
66 "{} - ERROR key={} latency={}ms: {}",
75 "{} - Queued message with key={} latency={}ms",
85 @ResponseStatus(HttpStatus.BAD_REQUEST)
86 public ErrorResponse illegalStateException(IllegalStateException e)
88 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());