Der REST-Producer ergänzt Header (Header `X-id` und seine `client.id`)
[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.web.bind.annotation.*;
8 import org.springframework.web.context.request.async.DeferredResult;
9
10 import javax.annotation.PreDestroy;
11 import java.math.BigInteger;
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         partition, // Partition
61         key,    // Key
62         value   // Value
63     );
64
65     record.headers().add("source", id.getBytes());
66     if (correlationId != null)
67     {
68       record.headers().add("id", BigInteger.valueOf(correlationId).toByteArray());
69     }
70
71     producer.send(record, (metadata, e) ->
72     {
73       long now = System.currentTimeMillis();
74       if (e == null)
75       {
76         // HANDLE SUCCESS
77         produced++;
78         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
79         log.debug(
80             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
81             id,
82             record.key(),
83             record.value(),
84             metadata.partition(),
85             metadata.offset(),
86             metadata.timestamp(),
87             now - time
88         );
89       }
90       else
91       {
92         // HANDLE ERROR
93         result.setErrorResult(new ProduceFailure(e));
94         log.error(
95             "{} - ERROR key={} timestamp={} latency={}ms: {}",
96             id,
97             record.key(),
98             metadata == null ? -1 : metadata.timestamp(),
99             now - time,
100             e.toString()
101         );
102       }
103     });
104
105     long now = System.currentTimeMillis();
106     log.trace(
107         "{} - Queued #{} key={} latency={}ms",
108         id,
109         value,
110         record.key(),
111         now - time
112     );
113
114     return result;
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 }