-
Notifications
You must be signed in to change notification settings - Fork 0
/
Consumer_class.py
47 lines (39 loc) · 1.57 KB
/
Consumer_class.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
from confluent_kafka import Consumer
from confluent_kafka.serialization import SerializationContext, MessageField
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer
import os
from dotenv import load_dotenv
load_dotenv()
def sasl_config():
return {
"bootstrap.servers": os.getenv("BOOTSTRAP_SERVER"),
"security.protocol": os.getenv("SECURITY_PROTOCOL"),
"sasl.mechanisms": os.getenv("SSL_MECHANISM"),
"sasl.username": os.getenv("API_KEY"),
"sasl.password": os.getenv("API_SECRET_KEY"),
"group.id": os.getenv("GROUP_ID"),
"auto.offset.reset": os.getenv("AUTO_OFFSET_RESET")
}
def schema_config():
return {
'url': os.getenv("ENDPOINT_URL"),
'basic.auth.user.info': f"{os.getenv('SCHEMA_REGISTRY_API_KEY')}:{os.getenv('SCHEMA_REGISTRY_API_SECRET_KEY')}"
}
def main():
mytopic='topic_1'
schema_registry = SchemaRegistryClient(schema_config())
schema_version = schema_registry.get_latest_version(mytopic+"-"+MessageField.VALUE)
schema=schema_version.schema
avrodeserial= AvroDeserializer(schema_registry, schema)
consumer = Consumer(sasl_config())
consumer.subscribe([mytopic])
while True:
msg = consumer.poll(1.0)
if msg is None:
continue
else:
value = avrodeserial(msg.value(), SerializationContext(mytopic, MessageField.VALUE))
print(value, msg.partition(), msg.offset())
consumer.close()
main()