1 package de.juplo.kafka;
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;
10 import javax.annotation.PreDestroy;
11 import java.util.concurrent.ExecutionException;
16 public class RestProducer
18 private final String id;
19 private final KafkaTemplate<String, Object> kafkaTemplate;
21 private long produced = 0;
24 ApplicationProperties properties,
25 KafkaTemplate<String, Object> kafkaTemplate)
27 this.id = properties.getClientId();
28 this.kafkaTemplate = kafkaTemplate;
31 @PostMapping(path = "{key}")
32 public DeferredResult<ProduceResult> message(
33 @PathVariable String key,
34 @RequestBody String value)
37 return send(key, new ClientMessage(key, value));
40 @PutMapping(path = "{key}")
41 public DeferredResult<ProduceResult> message(@PathVariable String key)
44 return send(key, new FooMessage(key, System.currentTimeMillis()));
47 @PostMapping(path = "/")
48 public DeferredResult<ProduceResult> greeting(
49 @RequestBody String name)
52 return send(name, new Greeting(name));
55 private DeferredResult<ProduceResult> send(String key, Object value)
57 DeferredResult<ProduceResult> result = new DeferredResult<>();
59 final long time = System.currentTimeMillis();
61 kafkaTemplate.sendDefault(key, value).addCallback(
64 long now = System.currentTimeMillis();
67 RecordMetadata metadata = sendResult.getRecordMetadata();
69 result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
71 "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
83 long now = System.currentTimeMillis();
86 result.setErrorResult(new ProduceFailure(e));
88 "{} - ERROR key={} timestamp=-1 latency={}ms: {}",
96 long now = System.currentTimeMillis();
98 "{} - Queued key={} latency={}ms",
108 @ResponseStatus(HttpStatus.BAD_REQUEST)
109 public ErrorResponse illegalStateException(IllegalStateException e)
111 return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
115 public void destroy() throws ExecutionException, InterruptedException
117 log.info("{} - Destroy!", id);
118 log.info("{}: Produced {} messages in total, exiting!", id, produced);