Setup von counting-consumer auf endless-consumer umgestellt
[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.MediaType;
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 import java.util.concurrent.ExecutorService;
15
16
17 @Slf4j
18 @RestController
19 public class RestProducer
20 {
21   private final String id;
22   private final String topic;
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
32     Properties props = new Properties();
33     props.put("bootstrap.servers", properties.getBootstrapServer());
34     props.put("client.id", properties.getClientId());
35     props.put("acks", properties.getAcks());
36     props.put("batch.size", properties.getBatchSize());
37     props.put("delivery.timeout.ms", 20000); // 20 Sekunden
38     props.put("request.timeout.ms",  10000); // 10 Sekunden
39     props.put("linger.ms", properties.getLingerMs());
40     props.put("compression.type", properties.getCompressionType());
41     props.put("key.serializer", StringSerializer.class.getName());
42     props.put("value.serializer", StringSerializer.class.getName());
43
44     this.producer = new KafkaProducer<>(props);
45   }
46
47   @PostMapping(path = "{key}")
48   public DeferredResult<ProduceResult> send(
49       @PathVariable String key,
50       @RequestBody String value)
51   {
52     DeferredResult<ProduceResult> result = new DeferredResult<>();
53
54     final long time = System.currentTimeMillis();
55
56     final ProducerRecord<String, String> record = new ProducerRecord<>(
57         topic,  // Topic
58         key,    // Key
59         value   // Value
60     );
61
62     producer.send(record, (metadata, e) ->
63     {
64       long now = System.currentTimeMillis();
65       if (e == null)
66       {
67         // HANDLE SUCCESS
68         produced++;
69         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
70         log.debug(
71             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
72             id,
73             record.key(),
74             record.value(),
75             metadata.partition(),
76             metadata.offset(),
77             metadata.timestamp(),
78             now - time
79         );
80       }
81       else
82       {
83         // HANDLE ERROR
84         result.setErrorResult(new ProduceFailure(e));
85         log.error(
86             "{} - ERROR key={} timestamp={} latency={}ms: {}",
87             id,
88             record.key(),
89             metadata == null ? -1 : metadata.timestamp(),
90             now - time,
91             e.toString()
92         );
93       }
94     });
95
96     long now = System.currentTimeMillis();
97     log.trace(
98         "{} - Queued #{} key={} latency={}ms",
99         id,
100         value,
101         record.key(),
102         now - time
103     );
104
105     return result;
106   }
107
108   @PreDestroy
109   public void destroy() throws ExecutionException, InterruptedException
110   {
111     log.info("{} - Destroy!", id);
112     log.info("{} - Closing the KafkaProducer", id);
113     producer.close();
114     log.info("{}: Produced {} messages in total, exiting!", id, produced);
115   }
116 }