简体   繁体   English

检查系统是否连接到Kafka

[英]Check If System Is Connected To Kafka

I need to write a smoke test in Java which validates whether the system is connected to kafka, 我需要在Java中编写一个冒烟测试,验证系统是否连接到kafka,

Does anyone have any idea? 有人有什么主意吗? I have found this post: 我发现这篇文章:

How to check whether Kafka Server is running? 如何检查Kafka Server是否正在运行?

But it's too complicated to do from a Java code and I don't think It's the direction i should use. 但是从Java代码中做起来太复杂了,我不认为这是我应该使用的方向。

Thanks in advance. 提前致谢。

I had the same question and I don't want to leave this question without any answer. 我有同样的问题,我不想在没有任何答案的情况下留下这个问题。 I read a lot about how I can check the connection and most of the answers I found was checking the connection with Zk, but I really want to check the connection directly with Kafka server. 我读了很多关于如何检查连接的内容,我发现的大部分答案都是检查与Zk的连接,但我真的想直接检查与Kafka服务器的连接。

What I did is to create a simple KafkaConsumer and list all the topics with listTopics() . 我所做的是创建一个简单的KafkaConsumer并列出listTopics()的所有主题。 If the connection is success, then you will get something as a return. 如果连接成功,那么您将得到一些回报。 Otherwise, you will get a TimeoutException . 否则,您将收到TimeoutException

  def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
    props.put("group.id", kafkaParams.get("group.id").get.toString)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    val simpleConsumer = new KafkaConsumer[String, String](props)
    simpleConsumer.listTopics()
  }

then you can wrap this method in a try-catch sentence to catch the exception. 然后你可以将这个方法包装在try-catch语句中以捕获异常。

You can check if the server is running by using this: 您可以使用以下命令检查服务器是否正在运行:

ZkClient zkClient = new ZkClient("your_zookeeper_server", 5000 /* ZOOKEEPER_SESSION_TIMEOUT */, 5000 /* ZOOKEEPER_CONNECTION_TIMEOUT */, ZKStringSerializer$.MODULE$);
List<Broker> brokers = scala.collection.JavaConversions.seqAsJavaList(zkUtils.getAllBrokersInCluster());
if (brokers.isEmpty()) {
    // No brokers available
} else {
    // There are brokers available
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM