- public SimpleConsumer(String broker, String topic, String groupId, String clientId)
- {
- Properties props = new Properties();
- props.put("bootstrap.servers", broker);
- props.put("group.id", groupId); // ID für die Offset-Commits
- props.put("client.id", clientId); // Nur zur Wiedererkennung
- props.put("partition.assignment.strategy", "org.apache.kafka.clients.consumer.CooperativeStickyAssignor");
- props.put("key.deserializer", StringDeserializer.class.getName());
- props.put("value.deserializer", StringDeserializer.class.getName());
-
- consumer = new KafkaConsumer<>(props);
-
- this.topic = topic;
- this.id = clientId;
- }
-
-
- public void run()
- {
- try
- {
- log.info("{} - Subscribing to topic test", id);
- consumer.subscribe(Arrays.asList("test"));
- running = true;
-
- while (true)
- {
- ConsumerRecords<String, String> records =
- consumer.poll(Duration.ofSeconds(1));
-
- log.info("{} - Received {} messages", id, records.count());
- for (ConsumerRecord<String, String> record : records)
- {
- consumed++;
- log.info(
- "{} - {}: {}/{} - {}={}",
- id,
- record.offset(),
- record.topic(),
- record.partition(),
- record.key(),
- record.value()
- );
- }
- }
- }
- catch(WakeupException e)
- {
- log.info("{} - Consumer was signaled to finish its work", id);
- }
- catch(Exception e)
- {
- log.error("{} - Unexpected error: {}", id, e.toString());
- }
- finally
- {
- running = false;
- log.info("{} - Closing the KafkaConsumer", id);
- consumer.close();
- log.info("{}: Consumed {} messages in total, exiting!", id, consumed);
- }
- }
-
-
- public static void main(String[] args) throws Exception
+ @KafkaListener(topics = "${simple.consumer.topic}")
+ private void handleRecord(
+ @Header(KafkaHeaders.RECEIVED_TOPIC)
+ String topic,
+ @Header(KafkaHeaders.RECEIVED_PARTITION_ID)
+ Integer partition,
+ @Header(KafkaHeaders.OFFSET)
+ Long offset,
+ @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY)
+ String key,
+ @Payload
+ String value)