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;
19 private final String id;
21 private final Map<Integer, AdderBusinessLogic> state = new HashMap<>();
25 public void accept(ConsumerRecord<String, String> record)
27 Integer partition = record.partition();
28 String user = record.key();
29 String message = record.value();
31 if (message.equals("CALCULATE"))
33 AdderResult result = state.get(partition).calculate(user);
34 log.info("{} - New result for {}: {}", id, user, result);
35 results.addResults(partition, user, result);
39 state.get(partition).addToSum(user, Integer.parseInt(message));
42 if (throttle.isPresent())
46 Thread.sleep(throttle.get().toMillis());
48 catch (InterruptedException e)
50 log.warn("{} - Intrerrupted while throttling: {}", id, e);
55 protected void addPartition(Integer partition, Map<String, AdderResult> state)
57 this.state.put(partition, new AdderBusinessLogic(state));
60 protected Map<String, AdderResult> removePartition(Integer partition)
62 return this.state.remove(partition).getState();
66 public Map<Integer, AdderBusinessLogic> getState()
71 public AdderBusinessLogic getState(Integer partition)
73 return state.get(partition);