简体   繁体   English

使用队列实现 Kafka 生产者消费者聊天

[英]Implement Kafka Producer Consumer Chat with Queue

I have created implemented Kafka Producer-Consumer messaging with Topic using python.How can I do the same with Queue so that the message will be only devilered to a single consumer.我已经使用 python 创建了实现的带有主题的 Kafka 生产者-消费者消息传递。我怎样才能对队列执行相同的操作,以便消息只会发送给单个消费者。

This is my Producer code这是我的生产者代码

# Import KafkaProducer from Kafka library
from kafka import KafkaProducer

# Define server with port
bootstrap_servers = ['localhost:9092']

# Define topic name where the message will publish
topicName = 'First_Topic'

# Initialize producer variable
producer = KafkaProducer(bootstrap_servers = bootstrap_servers)
i=1
for i in range(100):
# Publish text in defined topic
    message_data = input("Enter message ")

    producer.send(topicName,str.encode(message_data)  )

# Print message
    print("Message Sent")
i=i+1

And this is my consumer code.这是我的消费者代码。

from kafka import KafkaConsumer
consumer = KafkaConsumer(bootstrap_servers=['localhost:9092'], auto_offset_reset='earliest')
consumer.subscribe(['First_Topic'])

for msg in consumer:
    print("Message from Producer on Topic - "+msg.topic+":"+ msg.value.decode())

When producer produces a message on a Kafka topic it doesn't go to consumer directly instead it will go to Kafka broker first on a specific partition (which is like a persistent distributed queue).当生产者在 Kafka 主题上生成消息时,它不会 go 直接发送给消费者,而是首先在特定分区上发送 go 到 Kafka 代理(类似于持久分布式队列)。

How and how many consumers will get message will depend upon your consumer's setting.如何以及有多少消费者会收到消息将取决于您的消费者的设置。 One or more consumers can subscribe to same topic/partition depending upon your subscription scheme.根据您的订阅方案,一个或多个消费者可以订阅相同的主题/分区。 if you start multiple consumer using different consumer groupId (or no group Id at all) then all consumers will get same data.如果您使用不同的消费者 groupId(或根本没有组 ID)启动多个消费者,那么所有消费者将获得相同的数据。 if same group id is used for all consumers only one consumer will get messages from one partition.如果所有消费者使用相同的组 ID,则只有一个消费者会从一个分区获取消息。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM