主要存在两种方式:即自动创建还是手动创建。当配置auto.create.topics.enable=true时,则如果kafka发现该topic不存在的话,会按默认配置自动创建topic。当配置auto.create.topics.enable=false时,客户端需要提前创建好topic,才可以正确地往topic发送数据,创建topic的命令如下:
bin/kafka-topics.sh --create --zookeeperlocalhost:2181 --replication-factor [副本数目]
--partitions [分区数据] --topic[topic名字]
查看kafka-topics.sh脚本:
exec $(dirname $0)/kafka-run-class.sh kafka.admin.TopicCommand $@
最终执行的是TopicCommand类:
object TopicCommand {
def main(args: Array[String]): Unit = {
val opts = new TopicCommandOptions(args)
if(args.length == 0)
CommandLineUtils.printUsageAndDie(opts.parser, "Create, delete, describe, or change a topic.")
// should have exactly one action
val actions = Seq(opts.createOpt, opts.listOpt, opts.alterOpt, opts.describeOpt, opts.deleteOpt).count(opts.options.has _)
if(actions != 1)
CommandLineUtils.printUsageAndDie(opts.parser, "Command must include exactly one action: --list, --describe, --create, --alter or --delete")
opts.checkArgs()
val zkClient = new ZkClient(opts.options.valueOf(opts.zkConnectOpt), 30