bccc166de968854dce7dd44aa52f16553be844dd
[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.kafka.support.serializer.JsonSerializer;
9 import org.springframework.web.bind.annotation.*;
10 import org.springframework.web.context.request.async.DeferredResult;
11
12 import javax.annotation.PreDestroy;
13 import java.util.Properties;
14 import java.util.concurrent.ExecutionException;
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, ClientMessage> 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", JsonSerializer.class.getName());
43     props.put(JsonSerializer.TYPE_MAPPINGS, "message:" + ClientMessage.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       @RequestBody String value)
52   {
53     DeferredResult<ProduceResult> result = new DeferredResult<>();
54
55     final long time = System.currentTimeMillis();
56
57     final ProducerRecord<String, ClientMessage> record = new ProducerRecord<>(
58         topic,  // Topic
59         key,    // Key
60         new ClientMessage(key, value) // Value
61     );
62
63     producer.send(record, (metadata, e) ->
64     {
65       long now = System.currentTimeMillis();
66       if (e == null)
67       {
68         // HANDLE SUCCESS
69         produced++;
70         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
71         log.debug(
72             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
73             id,
74             record.key(),
75             record.value(),
76             metadata.partition(),
77             metadata.offset(),
78             metadata.timestamp(),
79             now - time
80         );
81       }
82       else
83       {
84         // HANDLE ERROR
85         result.setErrorResult(new ProduceFailure(e));
86         log.error(
87             "{} - ERROR key={} timestamp={} latency={}ms: {}",
88             id,
89             record.key(),
90             metadata == null ? -1 : metadata.timestamp(),
91             now - time,
92             e.toString()
93         );
94       }
95     });
96
97     long now = System.currentTimeMillis();
98     log.trace(
99         "{} - Queued #{} key={} latency={}ms",
100         id,
101         value,
102         record.key(),
103         now - time
104     );
105
106     return result;
107   }
108
109   @ExceptionHandler
110   @ResponseStatus(HttpStatus.BAD_REQUEST)
111   public ErrorResponse illegalStateException(IllegalStateException e)
112   {
113     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
114   }
115
116   @PreDestroy
117   public void destroy() throws ExecutionException, InterruptedException
118   {
119     log.info("{} - Destroy!", id);
120     log.info("{} - Closing the KafkaProducer", id);
121     producer.close();
122     log.info("{}: Produced {} messages in total, exiting!", id, produced);
123   }
124 }