Getting the last message sent to a kafka topic

后端 未结 2 1815
执念已碎
执念已碎 2021-01-06 13:01

I\'m new to Kafka and working on a prototype to connect a proprietary streaming service into Kafka.

I\'m looking to get the key of the last message sent on a topic a

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-06 14:00

    Check the record count and get the last message:

        // Poll so we know we're connected
        consumer.poll(100);
        // Get the assigned partitions
        Set assignedPartitions = consumer.assignment();
        // Seek to the end of those partitions
        consumer.seekToEnd(assignedPartitions);
    
        for (TopicPartition partition : assignedPartitions) {
            final long offset = consumer.committed(partition).offset();
            // Seek to the previous message
            consumer.seek(partition, offset - 1);
        }
    
        // Now get the last message
        ConsumerRecords records = consumer.poll(100);
        int size = records.count();
        int index = 0;
        for (ConsumerRecord record : records) {
            index = index + 1;
            if (index == size) {
                String value = record.value();
                System.out.println("Last Message = " + value);
            }
        }
        consumer.close();
    

提交回复
热议问题