Kafka 实战 - kafka 命令操作

本文详细介绍了在Kafka实战中,如何通过命令行进行Kafka和ZooKeeper集群的启动与停止,主题的管理(创建、查看、删除),以及消息的生产和消费。还涵盖了其他实用操作,如消费者组管理和主题配置修改。
摘要由CSDN通过智能技术生成

在 Kafka 实战中,命令行操作是管理和监控 Kafka 集群、主题及消息流的重要手段。以下是一些常用的 Kafka 命令操作示例,涵盖集群管理、主题管理、生产与消费消息等方面:

**1. 启动与停止 Kafka 和 ZooKeeper 集群

# 启动 ZooKeeper
$ bin/zookeeper-server-start.sh config/zookeeper.properties

# 停止 ZooKeeper
$ bin/zookeeper-server-stop.sh

# 启动 Kafka Broker(前台模式,按 Ctrl+C 停止)
$ bin/kafka-server-start.sh config/server.properties

# 启动 Kafka Broker(后台模式,作为守护进程)
$ bin/kafka-server-start.sh -daemon config/server.properties

# 停止 Kafka Broker
$ bin/kafka-server-stop.sh

**2. 主题管理

# 列出所有主题
$ bin/kafka-topics.sh --list --bootstrap-server localhost:9092

# 创建主题,指定分区数和副本因子
$ bin/kafka-topics.sh --create --bootstrap-server localhost:9092 \
    --replication-factor 3 --partitions 4 --topic my_topic

# 查看主题详情(包括分区、副本等信息)
$ bin/kafka-topics.sh --describe --bootstrap-server localhost:9092 --topic my_topic

# 删除主题(注意:这可能不会立即删除磁盘上的数据,需要清理或等待后台任务清理)
$ bin/kafka-topics.sh --delete --bootstrap-server localhost:9092 --topic my_topic

**3. 消息生产

# 使用控制台生产者发送消息到指定主题
$ bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my_topic

# 在控制台生产者提示符下,输入消息并按 Enter 发送
> This is a message
> Another message with key: key1

# 若要指定消息键(key)和值(value),可以使用 `--property` 选项:
$ bin/kafka-console-producer.sh --broker-list localhost:9092 --topic my_topic \
    --property parse.key=true --property key.separator=:
> key1:Value for key1
> key2:Value for key2

**4. 消息消费

# 使用控制台消费者从指定主题消费消息
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my_topic

# 消费最近的消息(默认行为)
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my_topic --from-latest

# 从特定偏移量开始消费
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my_topic --from-beginning

# 指定消费组并消费消息
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my_topic --group my_group

# 消费带有键的消息,并显示键和值
$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic my_topic \
    --property print.key=true --property key.separator=": "

**5. 其他实用操作

# 查看消费者组的消费情况(包括消费位移、Lag 等信息)
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --describe --group my_group

# 重置消费者组的消费位移(例如,将消费位移设置为最新)
$ bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --reset-offsets --to-latest \
    --group my_group --topic my_topic --execute

# 修改主题配置(如调整分区数或副本因子)
$ bin/kafka-configs.sh --bootstrap-server localhost:9092 --alter --entity-type topics \
    --entity-name my_topic --add-config retention.ms=604800000

请注意,上述命令中的 localhost:9092 应替换为实际 Kafka 集群的地址和端口。此外,某些操作可能需要具有相应的权限,尤其是涉及主题创建、删除和配置修改的操作。在生产环境中,通常会通过 Kafka 的管理工具或 API 进行更精细的权限控制和自动化管理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值