-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathschema_reg_avro_consumer1.py
More file actions
93 lines (75 loc) · 2.77 KB
/
Copy pathschema_reg_avro_consumer1.py
File metadata and controls
93 lines (75 loc) · 2.77 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from confluent_kafka import DeserializingConsumer
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer
from confluent_kafka.serialization import StringDeserializer
class User(object):
"""
User record
Args:
name (str): User's name
favorite_number (int): User's favorite number
favorite_color (str): User's favorite color
"""
def __init__(self, name=None, favorite_number=None, favorite_color=None):
self.name = name
self.favorite_number = favorite_number
self.favorite_color = favorite_color
def dict_to_user(obj, ctx):
"""
Converts object literal(dict) to a User instance.
Args:
obj (dict): Object literal(dict)
ctx (SerializationContext): Metadata pertaining to the serialization
operation.
"""
if obj is None:
return None
return User(name=obj['name'],
favorite_number=obj['favorite_number'],
favorite_color=obj['favorite_color'])
def main():
topic = "schema1"
schema_str = """
{
"namespace": "confluent.io.examples.serialization.avro",
"name": "User",
"type": "record",
"fields": [
{"name": "name", "type": "string"},
{"name": "favorite_number", "type": "int"},
{"name": "favorite_color", "type": "string"}
]
}
"""
sr_conf = {'url': "http://localhost:8081"}
schema_registry_client = SchemaRegistryClient(sr_conf)
avro_deserializer = AvroDeserializer(schema_str,
schema_registry_client,
dict_to_user)
string_deserializer = StringDeserializer('utf_8')
consumer_conf = {'bootstrap.servers': "localhost:9092",
'key.deserializer': string_deserializer,
'value.deserializer': avro_deserializer,
"group.id": "local",
'auto.offset.reset': "earliest"}
consumer = DeserializingConsumer(consumer_conf)
consumer.subscribe([topic])
while True:
try:
# SIGINT can't be handled when polling, limit timeout to 1 second.
msg = consumer.poll(1.0)
if msg is None:
continue
user = msg.value()
if user is not None:
print("User record {}: name: {}\n"
"\tfavorite_number: {}\n"
"\tfavorite_color: {}\n"
.format(msg.key(), user.name,
user.favorite_color,
user.favorite_number))
except KeyboardInterrupt:
break
consumer.close()
if __name__ == '__main__':
main()