-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkafka-prod.py
40 lines (29 loc) · 1.01 KB
/
kafka-prod.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
from confluent_kafka import Producer
import json
# Kafka broker address and topic name
bootstrap_servers = 'localhost:9092'
topic_name = 'orange_users_topic1'
# Create Kafka producer configuration
producer_config = {
'bootstrap.servers': bootstrap_servers
}
# Create Kafka producer
producer = Producer(producer_config)
# Path to the JSON file
json_file_path = 'people-100.json'
# Function to handle delivery report
def delivery_report(err, msg):
if err is not None:
print(f'Failed to deliver message: {err}')
else:
print(f'Message delivered to {msg.topic()} [{msg.partition()}]')
# Read JSON file and send each record as a message to Kafka topic
with open(json_file_path, 'r') as file:
records = json.load(file)
for record in records:
# Convert the record to JSON string
message = json.dumps(record)
# Produce the message to Kafka topic
producer.produce(topic_name, message, callback=delivery_report)
# close producer
producer.flush()