1 package de.juplo.kafka;
3 import lombok.RequiredArgsConstructor;
4 import lombok.extern.slf4j.Slf4j;
5 import org.apache.kafka.clients.consumer.ConsumerRecord;
7 import java.time.Duration;
8 import java.util.HashMap;
10 import java.util.Optional;
13 @RequiredArgsConstructor
15 public class ApplicationRecordHandler implements RecordHandler<String, String>
17 private final AdderResults results;
18 private final Optional<Duration> throttle;
20 private final Map<Integer, AdderBusinessLogic> state = new HashMap<>();
24 public void accept(ConsumerRecord<String, String> record)
26 Integer partition = record.partition();
27 String user = record.key();
28 String message = record.value();
30 if (message.equals("CALCULATE"))
32 AdderResult result = state.get(partition).calculate(user);
33 log.info("New result for {}: {}", user, result);
34 results.addResults(partition, user, result);
38 state.get(partition).addToSum(user, Integer.parseInt(message));
41 if (throttle.isPresent())
45 Thread.sleep(throttle.get().toMillis());
47 catch (InterruptedException e)
49 log.warn("Intrerrupted while throttling: {}", e);
54 protected void addPartition(Integer partition, Map<String, AdderResult> state)
56 this.state.put(partition, new AdderBusinessLogic(state));
59 protected Map<String, AdderResult> removePartition(Integer partition)
61 return this.state.remove(partition).getState();
65 public Map<Integer, AdderBusinessLogic> getState()
70 public AdderBusinessLogic getState(Integer partition)
72 return state.get(partition);