如何正确测试Kafka消费者组抵消操作?

时间:2019-05-06 21:03:04

标签: scala apache-kafka

我们有一个utils类,它将为给定的使用者组重置偏移量。这是当前代码(它有一个错误,无法很好地处理缺失的偏移量,这就是促使我深入研究的原因):

def resetOffsets(topics: Seq[String], groupId: String)
                  (implicit ec: ExecutionContext): Future[Map[TopicPartition, Long]] = {
    // TODO add error handling so that an empty reduceLeft is not happening
    Future {
      withConsumer(groupId) { consumer =>
        topics.map { topic =>
          val partitions = consumer.partitionsFor(topic)
          val tps = partitions.asScala.map(p => new TopicPartition(topic, p.partition())).asJava
          val offsets = consumer.beginningOffsets(tps).asScala
          consumer.commitSync(offsets.mapValues(new OffsetAndMetadata(_)).asJava)
          offsets
        }.reduce(_ ++ _).mapValues(l => l: Long).toMap
      }
    }
  }

我正在尝试建立一个测试工具,以断言这种行为实际上正在按照我的预期进行,但是却遇到了时间问题,未创建消费者群体等问题……

"A KafkaHelper" should "reset offsets" in {
    val kafkaHelper = new KafkaHelper(helperSettings)

    val groupId = GroupIdBase + s"_${new Random().nextInt(Integer.MAX_VALUE)}"

    println("Group id " + groupId)

    val consumer = createConsumer(groupId)

    consumer.assign(List(Partition).asJava)

    println(consumer.subscription())

    consumer.seek(Partition, 1L)

    consumer.commitSync()

    println(consumer.position(Partition))

    whenReady(kafkaHelper.resetOffsets(Seq(Topic), groupId)) { result =>
      result shouldEqual Map(Partition -> 0L)
      consumer.position(Partition) shouldEqual 0L
    }
  }

我要完成的工作只是简单地处理一个使用者组(或将其手动设置为一些偏移量),调用我的重置功能,然后断言该使用者组确实已重置为0。

我遇到的一些问题:

  • 直到我碰到whenReady区块,我的消费群体才被创建。这会导致subscribe方法出现问题,然后尝试检查当前分区。
  • 因此,为了解决这个问题,我尝试手动分配分区。我不确定这是个好主意。

如何围绕此代码正确创建测试工具,以便构建自动测试套件?我正在使用Kafka的本地docker实例进行测试。我最初开始使用https://github.com/manub/scalatest-embedded-kafka,因为这是我们用来测试许多面对Kafka的代码的方法,但是由于不知道他是否以与普通Kafka集群相同的方式实现基础行为,因此决定拒绝使用它

0 个答案:

没有答案
相关问题