Kafka Python
Kafka Python
Objectives
After completing this lab, you will be able to:
Note: You can copy the code by clicking the little copy button on the bottom right of the code
snippet below and then paste it, wherever you wish.
1. wget https://downloads.apache.org/kafka/3.8.0/kafka_2.13-3.8.0.tgz
Copied! Executed!
3. Extract Kafka from the zip file by running the command below.
1. 1
Copied! Executed!
about:blank 1/5
30/08/2024 11:28 about:blank
This creates a new directory kafka_2.13-3.8.0 in the current directory.
1. cd kafka_2.13-3.8.0
Copied! Executed!
2. Generate a Cluster UUID that will uniquely identify the Kafka cluster.
1. 1
1. KAFKA_CLUSTER_ID="$(bin/kafka-storage.sh random-uuid)"
Copied! Executed!
3. KRaft requires the log directories to be configured. Run the following command to configure the log
directories passing the cluster ID.
1. 1
Copied! Executed!
4. Now that KRaft is configured, you can start the Kafka server by running the following command.
1. 1
1. bin/kafka-server-start.sh config/kraft/server.properties
Copied!
Note: You can be sure it has started when you see an output contains messages that confirm the
Kafka Server started successfully.
1. cd kafka_2.13-3.8.0
Copied! Executed!
about:blank 2/5
30/08/2024 11:28 about:blank
1. 1
Copied!
1. 1
1. touch admin.py
Copied! Executed!
4. Click the button below to open the file in edit mode and paste the following content in the file and save
it.
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
Copied!
1. touch producer.py
Copied! Executed!
2. Click the button below to open the file in edit mode and paste the following content in the file and save
it.
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
about:blank 3/5
30/08/2024 11:28 about:blank
9. 9
Copied!
In the above code, the producer is sending across two messages through this code. These messages will be
received by the consumer.
1. 1
1. touch consumer.py
Copied! Executed!
2. Click the button below to open the file in edit mode and paste the following content in the file and save
it.
1. 1
2. 2
3. 3
4. 4
5. 5
6. 6
7. 7
8. 8
9. 9
10. 10
Copied!
1. python3 admin.py
2. python3 producer.py
Copied! Executed!
2. Open a new terminal and execute the following commands to run consumer.py:
1. 1
2. 2
1. cd kafka_2.13-3.8.0
2. python3 consumer.py
Copied! Executed!
3. Your consumer should print the messages sent by the producer as follows:
Practice Exercise
1. Create a new producer from bankbranch in a file named new_producer.py which will take user input
as long as the user wants and accept user input for the ATM number they want to transact with (1 or 2)
and stream the transaction.
2. Observe the consumer getting the events streamed by the producer in real time.
Authors
Ramesh Sana Reddy
Lavanya T S
Shreya Khurana
about:blank 5/5