-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple_consumer.py
42 lines (34 loc) · 1.18 KB
/
simple_consumer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from confluent_kafka import Consumer, KafkaError, TopicPartition
def consume_messages(topic: str = None, offset: int = None) -> None:
conf = {
'bootstrap.servers': 'localhost:19092',
'group.id': 'mygroup',
'auto.offset.reset': 'earliest'
}
consumer = Consumer(conf)
if offset is not None:
partitions = consumer.list_topics(topic).topics[topic].partitions
for partition in partitions:
consumer.assign([TopicPartition(topic, partition, offset)])
else:
consumer.subscribe([topic])
try:
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
if msg.error():
if msg.error().code() == KafkaError:
print('Reached end of partition')
else:
print(f'Error: {msg.error()}')
else:
print(f'Received message: {msg.value().decode("utf-8")}')
except KeyboardInterrupt:
pass
finally:
consumer.close()
# Читать с начала
consume_messages('test')
# Читать с определенного offset
# consume_messages('test', offset=5)