-
Notifications
You must be signed in to change notification settings - Fork 54
/
Copy pathconsumer.py
executable file
·49 lines (43 loc) · 1.76 KB
/
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
43
44
45
46
47
48
49
import sys
import os
from confluent_kafka import Consumer, KafkaException, KafkaError
if __name__ == '__main__':
topics = os.environ['CLOUDKARAFKA_TOPIC'].split(",")
# Consumer configuration
# See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
conf = {
'bootstrap.servers': os.environ['CLOUDKARAFKA_BROKERS'],
'group.id': "%s-consumer" % os.environ['CLOUDKARAFKA_USERNAME'],
'session.timeout.ms': 6000,
'default.topic.config': {'auto.offset.reset': 'smallest'},
'security.protocol': 'SASL_SSL',
'sasl.mechanisms': 'SCRAM-SHA-256',
'sasl.username': os.environ['CLOUDKARAFKA_USERNAME'],
'sasl.password': os.environ['CLOUDKARAFKA_PASSWORD']
}
c = Consumer(**conf)
c.subscribe(topics)
try:
while True:
msg = c.poll(timeout=1.0)
if msg is None:
continue
if msg.error():
# Error or event
if msg.error().code() == KafkaError._PARTITION_EOF:
# End of partition event
sys.stderr.write('%% %s [%d] reached end at offset %d\n' %
(msg.topic(), msg.partition(), msg.offset()))
elif msg.error():
# Error
raise KafkaException(msg.error())
else:
# Proper message
sys.stderr.write('%% %s [%d] at offset %d with key %s:\n' %
(msg.topic(), msg.partition(), msg.offset(),
str(msg.key())))
print(msg.value())
except KeyboardInterrupt:
sys.stderr.write('%% Aborted by user\n')
# Close down consumer to commit final offsets.
c.close()