6c852ce0bf8262e4da4cf29d88e465a137fd9e88
[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, Object> 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,
44         "message:" + ClientMessage.class.getName() + "," +
45         "greeting:" + Greeting.class.getName());
46
47     this.producer = new KafkaProducer<>(props);
48   }
49
50   @PostMapping(path = "{key}")
51   public DeferredResult<ProduceResult> message(
52       @PathVariable String key,
53       @RequestBody String value)
54   {
55     final ProducerRecord<String, Object> record = new ProducerRecord<>(
56         topic,  // Topic
57         key,    // Key
58         new ClientMessage(key, value) // Value
59     );
60
61     return send(record);
62   }
63
64   @PostMapping(path = "/")
65   public DeferredResult<ProduceResult> greeting(
66       @RequestBody String name)
67   {
68     final ProducerRecord<String, Object> record = new ProducerRecord<>(
69         topic,  // Topic
70         name,    // Key
71         new Greeting(name) // Value
72     );
73
74     return send(record);
75   }
76
77   private DeferredResult<ProduceResult> send(ProducerRecord<String, Object> record)
78   {
79     DeferredResult<ProduceResult> result = new DeferredResult<>();
80
81     final long time = System.currentTimeMillis();
82
83     producer.send(record, (metadata, e) ->
84     {
85       long now = System.currentTimeMillis();
86       if (e == null)
87       {
88         // HANDLE SUCCESS
89         produced++;
90         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
91         log.debug(
92             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
93             id,
94             record.key(),
95             record.value(),
96             metadata.partition(),
97             metadata.offset(),
98             metadata.timestamp(),
99             now - time
100         );
101       }
102       else
103       {
104         // HANDLE ERROR
105         result.setErrorResult(new ProduceFailure(e));
106         log.error(
107             "{} - ERROR key={} timestamp={} latency={}ms: {}",
108             id,
109             record.key(),
110             metadata == null ? -1 : metadata.timestamp(),
111             now - time,
112             e.toString()
113         );
114       }
115     });
116
117     long now = System.currentTimeMillis();
118     log.trace(
119         "{} - Queued key={} latency={}ms",
120         id,
121         record.key(),
122         now - time
123     );
124
125     return result;
126   }
127
128   @ExceptionHandler
129   @ResponseStatus(HttpStatus.BAD_REQUEST)
130   public ErrorResponse illegalStateException(IllegalStateException e)
131   {
132     return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
133   }
134
135   @PreDestroy
136   public void destroy() throws ExecutionException, InterruptedException
137   {
138     log.info("{} - Destroy!", id);
139     log.info("{} - Closing the KafkaProducer", id);
140     producer.close();
141     log.info("{}: Produced {} messages in total, exiting!", id, produced);
142   }
143 }