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;
15 @RequiredArgsConstructor
16 public class RestGateway
18 private final String id;
19 private final String topic;
20 private final Integer partition;
21 private final KafkaProducer<String, Integer> producer;
23 private long produced = 0;
25 @PostMapping(path = "{key}")
26 public DeferredResult<ProduceResult> send(
27 @PathVariable String key,
28 @RequestHeader(name = "X-id", required = false) Long correlationId,
29 @RequestBody Integer value)
31 DeferredResult<ProduceResult> result = new DeferredResult<>();
33 final long time = System.currentTimeMillis();
35 final ProducerRecord<String, Integer> record = new ProducerRecord<>(
37 partition, // Partition - Uses default-algorithm, if null
42 producer.send(record, (metadata, e) ->
44 long now = System.currentTimeMillis();
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={} timestamp={} latency={}ms: {}",
69 metadata == null ? -1 : metadata.timestamp(),
76 long now = System.currentTimeMillis();
78 "{} - Queued message with key={} latency={}ms",
88 @ResponseStatus(HttpStatus.BAD_REQUEST)
89 public ErrorResponse illegalStateException(IllegalStateException e)
91 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());