Initiale Version eines Gateways für die SumUp-Services
[demos/kafka/training] / src / main / java / de / juplo / kafka / RestGateway.java
diff --git a/src/main/java/de/juplo/kafka/RestGateway.java b/src/main/java/de/juplo/kafka/RestGateway.java
new file mode 100644 (file)
index 0000000..4549b8f
--- /dev/null
@@ -0,0 +1,91 @@
+package de.juplo.kafka;
+
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.kafka.clients.producer.KafkaProducer;
+import org.apache.kafka.clients.producer.ProducerRecord;
+import org.springframework.http.HttpStatus;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.context.request.async.DeferredResult;
+
+
+@Slf4j
+@RequestMapping
+@ResponseBody
+@RequiredArgsConstructor
+public class RestGateway
+{
+  private final String id;
+  private final String topic;
+  private final KafkaProducer<String, Integer> producer;
+
+  private long produced = 0;
+
+  @PostMapping(path = "{key}")
+  public DeferredResult<ProduceResult> send(
+      @PathVariable String key,
+      @RequestHeader(name = "X-id", required = false) Long correlationId,
+      @RequestBody Integer value)
+  {
+    DeferredResult<ProduceResult> result = new DeferredResult<>();
+
+    final long time = System.currentTimeMillis();
+
+    final ProducerRecord<String, Integer> record = new ProducerRecord<>(
+        topic,  // Topic
+        key,    // Key
+        value   // Value
+    );
+
+    producer.send(record, (metadata, e) ->
+    {
+      long now = System.currentTimeMillis();
+      if (e == null)
+      {
+        // HANDLE SUCCESS
+        produced++;
+        result.setResult(new ProduceSuccess(metadata.partition(), metadata.offset()));
+        log.debug(
+            "{} - Sent key={} message={} partition={}/{} timestamp={} latency={}ms",
+            id,
+            record.key(),
+            record.value(),
+            metadata.partition(),
+            metadata.offset(),
+            metadata.timestamp(),
+            now - time
+        );
+      }
+      else
+      {
+        // HANDLE ERROR
+        result.setErrorResult(new ProduceFailure(e));
+        log.error(
+            "{} - ERROR key={} timestamp={} latency={}ms: {}",
+            id,
+            record.key(),
+            metadata == null ? -1 : metadata.timestamp(),
+            now - time,
+            e.toString()
+        );
+      }
+    });
+
+    long now = System.currentTimeMillis();
+    log.trace(
+        "{} - Queued message with key={} latency={}ms",
+        id,
+        record.key(),
+        now - time
+    );
+
+    return result;
+  }
+
+  @ExceptionHandler
+  @ResponseStatus(HttpStatus.BAD_REQUEST)
+  public ErrorResponse illegalStateException(IllegalStateException e)
+  {
+    return new ErrorResponse(e.getMessage(), HttpStatus.BAD_REQUEST.value());
+  }
+}