简体   繁体   English

如何在Nodejs中检查Kafka主题的存在

[英]How to check the existence of Kafka topic in Nodejs

I am currently working with Nodejs and Kafka whereby a Nodejs server is set up to receive events and the data corresponding to the events are sent to Kafka.我目前正在使用 Nodejs 和 Kafka,其中设置了一个 Nodejs 服务器来接收事件,并将与事件对应的数据发送到 Kafka。 In Kafka, producer will create a topic accordingly and dynamically, if topic does not exist already.在 Kafka 中,如果主题不存在,生产者将相应地动态创建一个主题。 To do that, I want to check the existence of the topic, if it exists or not before creation.为此,我想在创建之前检查该主题是否存在。

I am currently using kafka-node module for kafka-node integrated functionalities.我目前正在将 kafka-node 模块用于 kafka-node 集成功能。 However, I could not find out any functionality which either tells about the existence of the topic or returns the list of all the topics currently exist in kafka.但是,我找不到任何可以说明主题存在或返回 kafka 中当前存在的所有主题列表的功能。

On searching on Internet, I found kafka-rest proxy which does help to know about this by fetching the current topics but I did not understand how to put that to use much.在 Internet 上搜索时,我找到了 kafka-rest 代理,它通过获取当前主题确实有助于了解这一点,但我不知道如何使用它。

Is there any other API via which I can achieve the stated functionality above?是否有任何其他 API 可以实现上述功能?

You can do both at the same time, actually.实际上,您可以同时执行这两项操作。 Just use the undocumented Client.loadMetadataForTopics() function.只需使用未记录的Client.loadMetadataForTopics()函数即可。 Like this:像这样:

var kafka = require('kafka-node');
var client = new kafka.Client("localhost:2181");

client.loadMetadataForTopics(["NonExistentTopic"], (err, resp) => {
  console.log(JSON.stringify(resp))
});

// [{"0":{"nodeId":0,"host":"host-001","port":9092}},{"error":["LeaderNotAvailable"],"metadata":{}}]

See the LeaderNotAvailable error?看到LeaderNotAvailable错误了吗? That means the topic doesn't exist.这意味着该主题不存在。 But -- assuming auto.topic.create.enable is set to true , then the call to loadMetadataForTopics will also create the topic.但是——假设auto.topic.create.enable设置为true ,那么对loadMetadataForTopics的调用也将创建主题。 So you get both in one call -- if you get the error , then the topic didn't exist and was created, if you don't get the error you get the actual topic metadata.因此,您可以在一次调用中获得两者——如果您收到error ,则该主题不存在并已创建,如果您没有收到错误,您将获得实际的主题元数据。

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

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