(1)编写生产者程序,以通用唯一标识符UUID作为消息,发送给主题assign_topic; (2)编写消费者程序1,订阅主题的分区0,只消费分区0数据; (3)编写消费者程序2,订阅主题的分区1,只消费分区1数据;
时间: 2023-12-13 12:05:38 浏览: 217
以下是Python代码示例,使用Kafka-Python库实现:
生产者程序:
```python
from kafka import KafkaProducer
import uuid
producer = KafkaProducer(bootstrap_servers='localhost:9092')
# 发送10条消息
for i in range(10):
message = str(uuid.uuid4()).encode('utf-8')
producer.send('assign_topic', message)
producer.flush()
```
消费者程序1:
```python
from kafka import KafkaConsumer
consumer = KafkaConsumer('assign_topic', bootstrap_servers='localhost:9092', group_id='group1',
auto_offset_reset='earliest', enable_auto_commit=True)
# 订阅分区0
consumer.assign([TopicPartition('assign_topic', 0)])
# 消费消息
for message in consumer:
print(f"Consumed from partition {message.partition}: {message.value.decode('utf-8')}")
```
消费者程序2:
```python
from kafka import KafkaConsumer
consumer = KafkaConsumer('assign_topic', bootstrap_servers='localhost:9092', group_id='group2',
auto_offset_reset='earliest', enable_auto_commit=True)
# 订阅分区1
consumer.assign([TopicPartition('assign_topic', 1)])
# 消费消息
for message in consumer:
print(f"Consumed from partition {message.partition}: {message.value.decode('utf-8')}")
```
以上代码示例仅供参考,具体实现方式可以根据实际需求进行调整。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)