简体   繁体   English

如何使用单个命令在 Apache Kafka 中创建主题列表

[英]How to create a list of topics in Apache Kafka using single command

As of now I am creating a topic one by one by using below command.截至目前,我正在使用以下命令一一创建主题。

sh ./bin/kafka-topics --create --zookeeper localhost:2181  --topic sdelivery --replication-factor 1 --partitions 1

Since I have 200+ topics to be created.因为我有 200 多个主题要创建。 Is there any way to create a list of topic with a single command?有没有办法用一个命令创建一个主题列表?

I am using 0.10.2 version of Apache Kafka.我正在使用 0.10.2 版本的 Apache Kafka。

This seems like more of a unix/bash question than a Kafka one: the xargs utility is specifically designed to run a command repeatedly from a list of arguments.这似乎更像是一个 unix/bash 问题,而不是 Kafka 问题:xargs 实用程序专门设计用于从参数列表重复运行命令。 In your specific case you could use:在您的具体情况下,您可以使用:

cat topic_list.txt | xargs -I % -L1 sh ./bin/kafka-topics --create --zookeeper localhost:2181 --topic % --replication-factor 1 --partitions 1

If you want to do a "dry run" and see what commands will be executed you can replace the sh with echo sh .如果您想进行“试运行”并查看将执行哪些命令,您可以将sh替换为echo sh

Alternatively you can just make sure that your config files have default topic settings of --replication-factor 1 and --partitions 1 and just allow those topics to be automatically created the first time you send a message to them.或者,您可以确保您的配置文件具有--replication-factor 1--partitions 1的默认主题设置,并允许在您第一次向它们发送消息时自动创建这些主题。

You could use Terraform or Kubernetes Operators which will not only help you create topics (with one command), but also manage them later.您可以使用 TerraformKubernetes Operators ,它们不仅可以帮助您创建主题(使用一个命令),还可以在以后管理它们。

But without custom solutions, you can use awk for this但是如果没有自定义解决方案,您可以为此使用awk

Create a file创建文件

$ cat /tmp/topics.txt
test1:1:1
test2:1:2

Then use system function to execute the kafka-topics script, and parse the file然后使用system函数执行kafka-topics脚本,解析文件

$ awk -F':' '{ system("./bin/kafka-topics.sh --create --zookeeper localhost:2181 --topic=" $1 " --partitions=" $2 " --replication-factor=" $3) }' /tmp/topics.txt
Created topic "test1".
Created topic "test2".

And we can see the topics are created我们可以看到主题已创建

$ ./bin/kafka-topics.sh --zookeeper localhost:2181 --list
test1
test2

Note: Hundreds of topics this quickly might overload Zookeeper, so might help to add a call to "; sleep 10" at the end.注意:这么快的数百个主题可能会使 Zookeeper 过载,因此在最后添加对"; sleep 10"的调用可能会有所帮助。

As of Kafka 3.0, the Zookeeper flag is replaced by bootstrap-servers.从 Kafka 3.0 开始,Zookeeper 标志被 bootstrap-servers 取代。

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

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