Professional Documents
Culture Documents
[1]:
import json
import kafka as k
Configuration Parameters
TODO: Change the configuration prameters to the appropriate values for your
setup.
In [2]:
config = dict(
bootstrap_servers=['192.168.10.9:9092'],
first_name='Adil',
last_name='Khan'
config['client_id'] = '{}{}'.format(
config['last_name'],
config['first_name']
config['topic_prefix'] = '{}{}'.format(
config['last_name'],
config['first_name']
config
{'bootstrap_servers': ['192.168.10.9:9092'],
Out[2]:
'first_name': 'Adil',
'last_name': 'Khan',
'client_id': 'KhanAdil',
'topic_prefix': 'KhanAdil'}
In [3]:
general_consumer = k.KafkaConsumer(
bootstrap_servers=config['bootstrap_servers']
In [4]:
general_consumer.topics()
{'KhanAdil-accelerations', 'KhanAdil-locations'}
Out[4]:
In [5]:
general_consumer.close()
In [7]:
def create_kafka_consumer(topics, config=config):
bootstrap_servers = config['bootstrap_servers']
client_id = config['client_id']
topic_prefix = config['topic_prefix']
return k.KafkaConsumer(
*topic_list,
client_id=client_id,
bootstrap_servers=bootstrap_servers,
auto_offset_reset='earliest',
enable_auto_commit=False,
value_deserializer=lambda x: json.loads(x)
In [8]:
consumer.subscription()
{'KhanAdil-accelerations', 'KhanAdil-locations'}
Out[8]:
The following function prints messages from the current consumer subscriptions. It will continue
until manually stopped.
In [9]:
def print_messages(consumer=consumer):
try:
msg_key = message.key.decode('utf-8')
else:
msg_key = ''
print('Message metadata:')
print('Message Value:')
print(msg_value)
print()
except KeyboardInterrupt:
print_messages()
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 0
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 1
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 2
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 3
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 4
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 5
Message Value:
"key1": "value1",
"key2": "value2"
Message metadata:
Topic: KhanAdil-locations
Partition: 0
Offset: 6
Message Value:
"key1": "value1",
"key2": "value2"
In [10]:
consumer.close()
In [ ]: