pythonKafka消费者订阅分区 在命令行启动Kafka后,手动创建’assgin_topic’主题,分区数量为2,执行命令如下: .\bin\windows\kafka-topics.bat --create --zookeeper localhost:2181 --replication-factor 1 --partitions 2 --topic assign_topic 1. 根据上面给出的主题,完成如下操作: (1)编写生产者程序,以通用唯一标识符UUID作为消息,发送给主题assign_topic; (2)编写消费者程序1,订阅主题的分区0,只消费分区0数据; (3)编写消费者程序2,订阅主题的分区1,只消费分区1数据;
时间: 2024-02-05 18:10:41 浏览: 115
以下是 Python Kafka 消费者订阅分区的代码示例:
生产者程序:
```python
from kafka import KafkaProducer
import uuid
producer = KafkaProducer(bootstrap_servers='localhost:9092')
for i in range(10):
message = str(uuid.uuid4()).encode('utf-8')
producer.send('assign_topic', message)
print(f"Sent message: {message}")
producer.close()
```
消费者程序1:
```python
from kafka import KafkaConsumer
consumer = KafkaConsumer('assign_topic', bootstrap_servers='localhost:9092',
group_id='my-group', auto_offset_reset='earliest',
enable_auto_commit=False, consumer_timeout_ms=1000)
# 订阅主题分区0
consumer.assign([TopicPartition('assign_topic', 0)])
try:
for message in consumer:
print(f"Received message from partition 0: {message.value}")
finally:
consumer.close()
```
消费者程序2:
```python
from kafka import KafkaConsumer
consumer = KafkaConsumer('assign_topic', bootstrap_servers='localhost:9092',
group_id='my-group', auto_offset_reset='earliest',
enable_auto_commit=False, consumer_timeout_ms=1000)
# 订阅主题分区1
consumer.assign([TopicPartition('assign_topic', 1)])
try:
for message in consumer:
print(f"Received message from partition 1: {message.value}")
finally:
consumer.close()
```
说明:
1. `KafkaProducer` 用于创建 Kafka 生产者,指定 Kafka 集群地址。
2. `uuid.uuid4()` 用于生成通用唯一标识符 UUID。
3. `producer.send()` 用于向主题发送消息。
4. `KafkaConsumer` 用于创建 Kafka 消费者,指定 Kafka 集群地址、消费者组、自动偏移重置策略、是否自动提交偏移量、消费超时时间等参数。
5. `consumer.assign()` 用于手动分配主题分区。
6. `for message in consumer` 用于消费消息。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![.zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)