将最后一条消息发送到kafka主题

时间:2017-11-07 18:19:03

标签: apache-kafka kafka-consumer-api kafka-producer-api

我是Kafka的新手,正在研究将专有流媒体服务连接到Kafka的原型。

我希望获取在主题上发送的最后一条消息的密钥,因为我们的内部流消费者需要使用其在连接时收到的最后一条消息的ID进行登录。

是否有可能使用KafkaProducer或KafkaConsumer来做到这一点?

我尝试使用Consumer执行以下操作,但在运行控制台使用者时,我会看到重播的邮件。

    // Poll so we know we're connected
    consumer.poll(100);
    // Get the assigned partitions
    Set<TopicPartition> 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<String, String> records = consumer.poll(100);
    for (ConsumerRecord<String, String> record : records) {
        lastKey = record.key();
    }
    consumer.close();

这是预期的行为,还是我走错了路?

2 个答案:

答案 0 :(得分:1)

问题出在行final long offset = consumer.committed(partition).offset()上,因为link api指的是committed方法是获取给定分区的the last committed offset,即:消费者告诉kafka服务器的最后一个偏移量它已经读过了。 所以,绝对会得到messages replayed,因为你总是从特定的偏移中读取。 我认为我只需删除第一个阻止。

答案 1 :(得分:-1)

检查记录计数并获取最后一条消息:

    // Poll so we know we're connected
    consumer.poll(100);
    // Get the assigned partitions
    Set<TopicPartition> 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<String, String> records = consumer.poll(100);
    int size = records.count();
    int index = 0;
    for (ConsumerRecord<String, String> record : records) {
        index = index + 1;
        if (index == size) {
            String value = record.value();
            System.out.println("Last Message = " + value);
        }
    }
    consumer.close();