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