如何关闭Kafka ConsumerConnector

时间:2014-09-30 18:09:50

标签: scala apache-kafka

我有一个从Kafka主题中提取消息的系统,当由于某些外部资源不可用而无法处理消息时,它会关闭消费者,将消息返回到主题,并在启动消费者之前等待一段时间再次。唯一的问题是,关闭不起作用。这是我在日志中看到的内容:

  

2014-09-30 08:24:10,918 - com.example.kafka.KafkaConsumer [info] - [application-akka.actor.workflow-context-8]关闭主题新问题报告的kafka消费者   2014-09-30 08:24:10,927 - clients.kafka.ProblemReportObserver [info] - [application-akka.actor.workflow-context-8] Consumer shutdown   2014-09-30 08:24:11,946 - clients.kafka.ProblemReportObserver [warn] - [application-akka.actor.workflow-context-8]将7410-1412090624000发送回队列   2014-09-30 08:24:12,021 - clients.kafka.ProblemReportObserver [debug] - [kafka-akka.actor.kafka-consumer-worker-context-9]来自分区0的消息:key = 7410-1412090624000,msg = 7410-1412090624000

这里有几层工作,但重要的代码是:

KafkaConsumer.scala

protected def consumer: ConsumerConnector = Consumer.create(config.asKafkaConfig)
def shutdown() = {
  logger.info(s"Shutting down kafka consumer for topic ${config.topic}")
  consumer.shutdown()
}

在观察消息的例程中:

(processor ? ProblemReportRequest(problemReportKey)).map {
  case e: ConnectivityInterruption =>
    val backoff = 10.seconds
    logger.warn(s"Can't connect to essential services, pausing for $backoff", e)
    stop()
    // XXX: Shutdown isn't instantaneous, so returning has to happen after a delay.
    // Unfortunately, there's still a race condition here, plus there's a chance the
    // system will be shut down before the message has been returned.
    system.scheduler.scheduleOnce(100 millis) { returnMessage(message) }
    system.scheduler.scheduleOnce(backoff) { start() }
    false
  case e: Exception => returnMessage(message, e)
  case _ => true
}.recover { case e => returnMessage(message, e) }

停止方法:

def stop() = {
  if (consumerRunning.get()) {
    consumer.shutdown()
    consumerRunning.compareAndSet(true, false)
    logger.info("Consumer shutdown")
  } else {
    logger.info("Consumer is already shutdown")
  }
  !consumerRunning.get()
}

这是一个错误,还是我做错了?

1 个答案:

答案 0 :(得分:1)

因为consumerdef。它会创建一个新的Kafka实例,并在您调用它时将其关闭,如consumer.shutdown()。将consumer改为val