feat: keys example
This commit is contained in:
@@ -0,0 +1,33 @@
|
||||
# Generates traaffic to be put into the topic
|
||||
|
||||
from kafka import KafkaProducer
|
||||
import time
|
||||
|
||||
# make a topic
|
||||
topic_name = "keys-topic" # same as the one made via script
|
||||
|
||||
# producer instance
|
||||
producer = KafkaProducer(
|
||||
bootstrap_servers='localhost:9092') # advertised listener
|
||||
|
||||
try:
|
||||
i = 0
|
||||
users = ['Alice', 'Bob', 'Charlie']
|
||||
|
||||
while True:
|
||||
for user in users:
|
||||
message = f"Message {i} from {user}"
|
||||
|
||||
# add the user bytes as key
|
||||
meta = producer.send(topic_name, key=user.encode('utf-8'), value=message.encode(
|
||||
# wait for ack, synchronous so NEVER use in prod
|
||||
'utf-8')).get()
|
||||
print(
|
||||
f"Sent: {message} with key: {user} to partition: {meta.partition}")
|
||||
|
||||
i += 1
|
||||
time.sleep(1) # 1 message per second
|
||||
except KeyboardInterrupt:
|
||||
print("Stopping producer...")
|
||||
finally:
|
||||
producer.close()
|
||||
Reference in New Issue
Block a user