一、基本shell操作
1)查看當前服務器中的所有topic
[root@hadoop102 kafka]$ bin/kafka-topics.sh --zookeeper hadoop102:2181 --list
2)創建topic
[root@hadoop102 kafka]$ bin/kafka-topics.sh --zookeeper hadoop102:2181 \
--create --replication-factor 3 --partitions 1 --topic first
選項說明:
–topic 定義topic名
–replication-factor 定義副本數
–partitions 定義分區數
3)刪除topic
[root@hadoop102 kafka]$ bin/kafka-topics.sh --zookeeper hadoop102:2181 \
--delete --topic first
需要server.properties中設置delete.topic.enable=true否則只是標記刪除或者直接重啓。
4)發送消息
[root@hadoop102 kafka]$ bin/kafka-console-producer.sh \
--broker-list hadoop102:9092 --topic first
>hello world
>root root
5)消費消息
[root@hadoop103 kafka]$ bin/kafka-console-consumer.sh \
--zookeeper hadoop102:2181 --from-beginning --topic first
–from-beginning:會把first主題中以往所有的數據都讀取出來。根據業務場景選擇是否增加該配置。
6)查看某個Topic的詳情
[root@hadoop102 kafka]$ bin/kafka-topics.sh --zookeeper hadoop102:2181 \
--describe --topic first
7)修改分區數
[root@hadoop102 kafka]$ bin/kafka-topics.sh --zookeeper
hadoop102:2181 --alter --topic first --partitions 6
二、消費者組
1.需求:
測試同一個消費者組中的消費者,同一時刻只能有一個消費者消費。
2.案例實操
(1)在 hadoop102、hadoop103 上修改/opt/module/kafka/config/consumer.properties 配置
文件中的 group.id 屬性爲任意組名。
[root@hadoop103 config]$ vi consumer.properties
group.id=ccjy
(2)在 hadoop102、hadoop103 上分別啓動消費者
[root@hadoop102 kafka]$ bin/kafka-console-consumer.sh \
--zookeeper hadoop102:2181 --topic first --consumer.config
config/consumer.properties
[root@hadoop103 kafka]$ bin/kafka-console-consumer.sh --
bootstrap-server hadoop102:9092 --topic first --consumer.config
config/consumer.properties
(3)在 hadoop104 上啓動生產者
[root@hadoop104 kafka]$ bin/kafka-console-producer.sh \
--broker-list hadoop102:9092 --topic first
>hello world
(4)查看 hadoop102 和 hadoop103 的接收者。
同一時刻只有一個消費者接收到消息