2f2b18c6448232309ad70da377b94667909743df
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestGateway.java
1 package de.juplo.kafka;
2
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;
13
14
15 @Slf4j
16 @RequestMapping
17 @ResponseBody
18 @RequiredArgsConstructor
19 public class RestGateway
20 {
21   private final String id;
22   private final Integer partition;
23   private final KafkaTemplate<String, Integer> kafkaTemplate;
24
25   private long produced = 0;
26
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)
32   {
33     DeferredResult<ProduceResult> result = new DeferredResult<>();
34
35     final long time = System.currentTimeMillis();
36
37     ListenableFuture<SendResult<String, Integer>> future =
38         kafkaTemplate.send(null, partition, key, value);
39
40     long now = System.currentTimeMillis();
41
42     future.addCallback(
43         sendResult ->
44         {
45           // HANDLE SUCCESS
46           produced++;
47           RecordMetadata metadata = sendResult.getRecordMetadata();
48           ProducerRecord<String, Integer> record = sendResult.getProducerRecord();
49           result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
50           log.debug(
51               "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
52               id,
53               record.key(),
54               record.value(),
55               metadata.partition(),
56               metadata.offset(),
57               metadata.timestamp(),
58               now - time
59           );
60         },
61         e->
62         {
63           // HANDLE ERROR
64           result.setErrorResult(new ProduceFailure(e));
65           log.error(
66               "{} - ERROR key={} latency={}ms: {}",
67               id,
68               key,
69               now - time,
70               e.toString()
71           );
72         });
73
74     log.trace(
75         "{} - Queued message with key={} latency={}ms",
76         id,
77         key,
78         now - time
79     );
80
81     return result;
82   }
83
84   @ExceptionHandler
85   @ResponseStatus(HttpStatus.BAD_REQUEST)
86   public ErrorResponse illegalStateException(IllegalStateException e)
87   {
88     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
89   }
90 }