1 package de.juplo.kafka.payment.transfer.domain;
4 import com.fasterxml.jackson.core.JsonProcessingException;
5 import com.fasterxml.jackson.databind.ObjectMapper;
6 import lombok.RequiredArgsConstructor;
7 import lombok.extern.slf4j.Slf4j;
8 import org.apache.kafka.clients.producer.KafkaProducer;
9 import org.apache.kafka.clients.producer.ProducerRecord;
10 import org.springframework.http.ResponseEntity;
13 import java.util.UUID;
15 import static de.juplo.kafka.payment.transfer.domain.Transfer.State.*;
19 @RequiredArgsConstructor
20 public class TransferService
22 private final TransferRepository repository;
23 private final KafkaProducer<String, String> producer;
24 private final ObjectMapper mapper;
25 private final String topic;
27 public synchronized void initiate(Transfer transfer)
30 .get(transfer.getId())
34 if (!transfer.equals(stored))
35 throw new IllegalArgumentException(
36 "Re-Initiation of transfer with different data: old=" +
41 if (stored.getState() == FAILED)
43 repository.update(transfer.getId(), FAILED, SENT);
44 log.info("Resending faild transfer: " + stored);
50 repository.store(transfer);
56 private void send(Transfer transfer)
60 ProducerRecord<String, String> record =
63 Long.toString(transfer.getId()),
64 mapper.writeValueAsString(transfer));
66 producer.send(record, (metadata, exception) ->
70 log.debug("Sent {} to {}/{}:{}", transfer, metadata.topic(), metadata.partition(), metadata.offset());
71 repository.update(transfer.getId(), SENT, PENDING);
75 log.error("Could not send {}: {}", transfer, exception.getMessage());
76 repository.update(transfer.getId(), SENT, FAILED);
80 catch (JsonProcessingException e)
82 throw new RuntimeException("Could not convert " + transfer, e);