56758f8151dc662c597387fbec599048ddb6aa56
[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.RecordMetadata;
5 import org.springframework.http.HttpStatus;
6 import org.springframework.kafka.core.KafkaTemplate;
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.util.concurrent.ExecutionException;
12
13
14 @Slf4j
15 @RestController
16 public class RestProducer
17 {
18   private final String id;
19   private final String topic;
20   private final KafkaTemplate<String, Object> kafkaTemplate;
21
22   private long produced = 0;
23
24   public RestProducer(
25       ApplicationProperties properties,
26       KafkaTemplate<String, Object> kafkaTemplate)
27   {
28     this.id = properties.getClientId();
29     this.topic = properties.getTopic();
30     this.kafkaTemplate = kafkaTemplate;
31   }
32
33   @PostMapping(path = "{key}")
34   public DeferredResult<ProduceResult> message(
35       @PathVariable String key,
36       @RequestBody String value)
37   {
38     key = key.trim();
39     return send(key, new ClientMessage(key, value));
40   }
41
42   @PutMapping(path = "{key}")
43   public DeferredResult<ProduceResult> message(@PathVariable String key)
44   {
45     key = key.trim();
46     return send(key, new FooMessage(key, System.currentTimeMillis()));
47   }
48
49   @PostMapping(path = "/")
50   public DeferredResult<ProduceResult> greeting(
51       @RequestBody String name)
52   {
53     name = name.trim();
54     return send(name, new Greeting(name));
55   }
56
57   private DeferredResult<ProduceResult> send(String key, Object value)
58   {
59     DeferredResult<ProduceResult> result = new DeferredResult<>();
60
61     final long time = System.currentTimeMillis();
62
63     kafkaTemplate.send(topic, key, value).addCallback(
64       (sendResult) ->
65       {
66         long now = System.currentTimeMillis();
67
68         // HANDLE SUCCESS
69         RecordMetadata metadata = sendResult.getRecordMetadata();
70         produced++;
71         result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
72         log.debug(
73             "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
74             id,
75             key,
76             value,
77             metadata.partition(),
78             metadata.offset(),
79             metadata.timestamp(),
80             now - time
81         );
82       },
83       (e) ->
84       {
85         long now = System.currentTimeMillis();
86
87         // HANDLE ERROR
88         result.setErrorResult(new ProduceFailure(e));
89         log.error(
90             "{} - ERROR key={} timestamp=-1 latency={}ms: {}",
91             id,
92             key,
93             now - time,
94             e.toString()
95         );
96       });
97
98     long now = System.currentTimeMillis();
99     log.trace(
100         "{} - Queued key={} latency={}ms",
101         id,
102         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("{}: Produced {} messages in total, exiting!", id, produced);
121   }
122 }