Kafka中Topic的操作。
kafka集群安装好了后我们就可以往kafka中添加一些数据。首先我们看下如何创建topic,以及针对topic的一些操作。
新增Topic:指定2个分区,2个副本。 注意:副本数不能大于集群中Broker的数量。因为每个partition的副本必须保存在不同的broker,否则没有意义,如果partition的副本都保存在同一个broker,那么这个broker挂了,则partition数据依然会丢失。由于这里我使用的是3个节点的kafka集群,所以副本数我就暂时设置为2,最大可以设置为3。
如果你们用的是单机kafka的话,这里的副本数就只能设置为1。
#创建topic
[root@master kafka]# cd $KAFKA_HOME
[root@bigdata01 kafka_2.12-2.4.1]# bin/kafka-topics.sh --create --zookeeper master:2181 --partitions 2 --replication-factor 2 --topic hello
Created topic hello.
[root@master kafka]# bin/kafka-topics.sh --create --zookeeper master:2181 --partitions 2 --replication-factor 2 --topic mytopic1
Created topic mytopic1.
#查看topic列表
[root@master kafka]# bin/kafka-topics.sh --list --zookeeper master:2181
hello
mytopic1
#查看topic详情
[root@master kafka]# bin/kafka-topics.sh --describe --zookeeper master:2181 --topic mytopic1
Topic: mytopic1 PartitionCount: 2 ReplicationFactor: 2 Configs:
Topic: mytopic1 Partition: 0 Leader: 2 Replicas: 2,1 Isr: 2,1
Topic: mytopic1 Partition: 1 Leader: 0 Replicas: 0,2 Isr: 0,2
#修改Topic:修改Topic的partition数量,只能增加
[root@master kafka]# bin/kafka-topics.sh --alter --zookeeper master:2181 --partitions 5 --topic mytopic1
WARNING: If partitions are increased for a topic that has a key, the partition logic or ordering of the messages will be affected
Adding partitions succeeded!
[root@master kafka]# bin/kafka-topics.sh --describe --zookeeper master:2181 --topic mytopic1
Topic: mytopic1 PartitionCount: 5 ReplicationFactor: 2 Configs:
Topic: mytopic1 Partition: 0 Leader: 2 Replicas: 2,1 Isr: 2,1
Topic: mytopic1 Partition: 1 Leader: 0 Replicas: 0,2 Isr: 0,2
Topic: mytopic1 Partition: 2 Leader: 1 Replicas: 1,2 Isr: 1,2
Topic: mytopic1 Partition: 3 Leader: 2 Replicas: 2,1 Isr: 2,1
Topic: mytopic1 Partition: 4 Leader: 0 Replicas: 0,2 Isr: 0,2
#删除Topic:删除Kafka中的指定Topic
#删除操作是不可逆的,删除Topic会删除它里面的所有数据
[root@master kafka]# bin/kafka-topics.sh --delete --zookeeper master:2181 --topic mytopic1
Topic mytopic1 is marked for deletion.
Note: This will have no impact if delete.topic.enable is not set to true.
[root@master kafka]# bin/kafka-topics.sh --list --zookeeper master:2181
hello
注意:Kafka从1.0.0开始默认开启了删除操作,之前的版本只会把Topic标记为删除状态,需要设置delete.topic.enable为true才可以真正删除。
如果不想开启删除功能,可以设置delete.topic.enable为false,这样删除topic的时候只会把它标记为删除状态,此时这个topic依然可以正常使用。 delete.topic.enable可以配置在server.properties文件中。