0f356001aac76aae31bcab805ae0c69e2b868f24
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestProducer.java
1 package de.juplo.kafka;
2
3 import lombok.extern.slf4j.Slf4j;
4 import org.apache.kafka.clients.producer.KafkaProducer;
5 import org.apache.kafka.clients.producer.ProducerRecord;
6 import org.apache.kafka.common.serialization.StringSerializer;
7 import org.springframework.http.HttpStatus;
8 import org.springframework.web.bind.annotation.*;
9 import org.springframework.web.context.request.async.DeferredResult;
10
11 import javax.annotation.PreDestroy;
12 import java.util.Properties;
13 import java.util.concurrent.ExecutionException;
14
15
16 @Slf4j
17 @RestController
18 public class RestProducer
19 {
20   private final String id;
21   private final String topic;
22   private final Integer partition;
23   private final KafkaProducer<String, String> producer;
24
25   private long produced = 0;
26
27   public RestProducer(ApplicationProperties properties)
28   {
29     this.id = properties.getClientId();
30     this.topic = properties.getTopic();
31     this.partition = properties.getPartition();
32
33     Properties props = new Properties();
34     props.put("bootstrap.servers", properties.getBootstrapServer());
35     props.put("client.id", properties.getClientId());
36     props.put("acks", properties.getAcks());
37     props.put("batch.size", properties.getBatchSize());
38     props.put("delivery.timeout.ms", 20000); // 20 Sekunden
39     props.put("request.timeout.ms",  10000); // 10 Sekunden
40     props.put("linger.ms", properties.getLingerMs());
41     props.put("compression.type", properties.getCompressionType());
42     props.put("key.serializer", StringSerializer.class.getName());
43     props.put("value.serializer", StringSerializer.class.getName());
44
45     this.producer = new KafkaProducer<>(props);
46   }
47
48   @PostMapping(path = "{key}")
49   public DeferredResult<ProduceResult> send(
50       @PathVariable String key,
51       @RequestHeader(name = "X-id", required = false) Long correlationId,
52       @RequestBody String value)
53   {
54     DeferredResult<ProduceResult> result = new DeferredResult<>();
55
56     final long time = System.currentTimeMillis();
57
58     final ProducerRecord<String, String> record = new ProducerRecord<>(
59         topic,  // Topic
60         key,    // Key
61         value   // Value
62     );
63
64     producer.send(record, (metadata, e) ->
65     {
66       long now = System.currentTimeMillis();
67       if (e == null)
68       {
69         // HANDLE SUCCESS
70         produced++;
71         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
72         log.debug(
73             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
74             id,
75             record.key(),
76             record.value(),
77             metadata.partition(),
78             metadata.offset(),
79             metadata.timestamp(),
80             now - time
81         );
82       }
83       else
84       {
85         // HANDLE ERROR
86         result.setErrorResult(new ProduceFailure(e));
87         log.error(
88             "{} - ERROR key={} timestamp={} latency={}ms: {}",
89             id,
90             record.key(),
91             metadata == null ? -1 : metadata.timestamp(),
92             now - time,
93             e.toString()
94         );
95       }
96     });
97
98     long now = System.currentTimeMillis();
99     log.trace(
100         "{} - Queued #{} key={} latency={}ms",
101         id,
102         value,
103         record.key(),
104         now - time
105     );
106
107     return result;
108   }
109
110   @ExceptionHandler
111   @ResponseStatus(HttpStatus.BAD_REQUEST)
112   public ErrorResponse illegalStateException(IllegalStateException e)
113   {
114     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
115   }
116
117   @PreDestroy
118   public void destroy() throws ExecutionException, InterruptedException
119   {
120     log.info("{} - Destroy!", id);
121     log.info("{} - Closing the KafkaProducer", id);
122     producer.close();
123     log.info("{}: Produced {} messages in total, exiting!", id, produced);
124   }
125 }