如何使用Sarama Go Kafka Consumer从最新偏移量消费

如何使用Sarama Go Kafka Consumer从最新偏移量消费,go,apache-kafka,kafka-consumer-api,sarama,Go,Apache Kafka,Kafka Consumer Api,Sarama,我有三个问题: “最古老的偏移量”是什么意思?最早的偏移量并不意味着偏移量为0 //OffsetOldest代表代理上可用的最早的偏移量 //分区。 偏移量int64=-2 假设 A.在同一台机器上运行的三个代理 B.消费者组只有一个消费者线程 C.消费者配置OffsetOldest标志。 D.已经产生了100个MSG,目前消费者线程消耗了90个MSG 因此,如果使用者线程重新启动,那么该使用者将从哪个偏移开始消费?是91还是0 在我们下面的代码中,每次消费者启动时,它似乎都会重新收集消息。但事

我有三个问题:

  • “最古老的偏移量”是什么意思?最早的偏移量并不意味着偏移量为0
  • //OffsetOldest代表代理上可用的最早的偏移量
    //分区。
    偏移量int64=-2

  • 假设

    A.在同一台机器上运行的三个代理
    B.消费者组只有一个消费者线程
    C.消费者配置OffsetOldest标志。
    D.已经产生了100个MSG,目前消费者线程消耗了90个MSG

    因此,如果使用者线程重新启动,那么该使用者将从哪个偏移开始消费?是91还是0

  • 在我们下面的代码中,每次消费者启动时,它似乎都会重新收集消息。但事实上,这种情况并不总是发生。为什么重新启动后(不是全部)会发生几次重新消耗

  • 否。应用保留策略时,会从主题中删除旧邮件。因此,最早的偏移可能不是第一个偏移(即
    0

  • 这取决于您的配置。基本上,您有3种选择:

    • 最早的
      偏移开始消费
    • 最新的
      偏移量开始消费
    • 从特定偏移量开始消费
  • 您必须使用
    sarama.OffsetOldest
    。从


  • 我找到了答案。对于问题#2,除非您的消费补偿已过期,否则您不会从提前/最新补偿中消费!!!
     func (this *consumerGroupHandler) ConsumeClaim(session 
     sarama.ConsumerGroupSession, claim sarama.ConsumerGroupClaim) error {
              for message := range claim.Messages() {
              this.handler(message)
             session.MarkMessage(message, "")
        }
    
        return nil
    }
    
    ctx := context.Background()
    conf := sarama.NewConfig()
    
    conf.Version = sarama.V2_0_0_0
    conf.Consumer.Offsets.Initial = sarama.OffsetOldest
    conf.Consumer.Return.Errors = true
    
    consumer, err := sarama.NewConsumerGroup(strings.Split(app.Config().KafkaBrokers, ","), groupId, conf)
    if err != nil {
        logger.Error("NewConsumerGroupFromClient(%s) error: %v", groupId, err)
        return
    }
    
     const (
            // OffsetNewest stands for the log head offset, i.e. the offset that will be
            // assigned to the next message that will be produced to the partition. You
            // can send this to a client's GetOffset method to get this offset, or when
            // calling ConsumePartition to start consuming new messages.
            OffsetNewest int64 = -1
            // OffsetOldest stands for the oldest offset available on the broker for a
            // partition. You can send this to a client's GetOffset method to get this
            // offset, or when calling ConsumePartition to start consuming from the
            // oldest offset that is still available on the broker.
            OffsetOldest int64 = -2
        )