没有消费者连接时,Kafka 代理可以保留消息吗?

Can a Kafka broker retain messages while there are no consumers connected?

我正在尝试构建一个 pub/sub 应用程序,并且我正在探索最好的工具。我目前正在查看 Kafka 并且已经 运行 有了一个小的演示应用程序。但是,我 运行 正在陷入概念性问题。

我有制作人(Java代码):

    String topicName = "MyTopic;
    String key = "MyKey";

    Properties props = new Properties();
    props.put("bootstrap.servers", "localhost:9092,localhost:9093");
    props.put("acks", "all");
    props.put("key.serializer","org.apache.kafka.common.serialization.StringSerializer");
    props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
    Producer<String, byte[]> producer = new KafkaProducer <String, byte[]>(props);

    byte[] data = <FROM ELSEWHERE>;
    ProducerRecord<String, byte[]> record = new ProducerRecord<String, byte[]>(topicName, key, data);

    try {
        RecordMetadata result = producer.send(record).get();
    }
    catch (Exception e) {
        // Nothing for now
    }
    producer.close();

当我通过 Kakfa 命令行工具启动消费者时:

kafka-console-consumer --bootstrap-server localhost:9092 --topic MyTopic

然后我执行生产者代码,我看到数据消息显示在我的消费者终端上。

但是,如果我不是运行消费者在执行生产者之前,消息出现"lost".当我启动消费者时(执行生产者之后),消费者终端没有任何显示。

有谁知道在没有消费者连接的情况下是否可以让 Kafka 代理 保留 消息?如果可以,怎么做?

--from-beginning 附加到控制台消费者命令,使其从最早的偏移量开始消费。这实际上是关于由config auto.offset.reset 控制的偏移重置策略。这是此配置的含义:

What to do when there is no initial offset in Kafka or if the current offset does not exist any more on the server (e.g. because that data has been deleted):

earliest: automatically reset the offset to the earliest offset

latest: automatically reset the offset to the latest offset

none: throw exception to the consumer if no previous offset is found for the consumer's group anything else: throw exception to the consumer.