This document describes how to access CKafka to send/receive messages with the SDK for Python in a VPC.
Upload the pythonkafkademo
in the downloaded demo to the Linux server, log in to the server, and enter the pythonkafkademo
directory.
Run the following command to install:
pip install kafka-python
producer.py
.#coding:utf8
from kafka import KafkaProducer
import json
producer = KafkaProducer(
bootstrap_servers = ['$domainName:$port'],
api_version = (0,10,0)
)
message = "Hello World! Hello Ckafka!"
msg = json.dumps(message).encode()
producer.send('topic_name',value = msg)
print("produce message " + message + " success.")
producer.close()
Parameter | Description |
---|---|
bootstrap_servers | Accessed network, which can be copied in the **Network** column in the Access Mode section on the instance details page in the console.![]() |
topic_name | Topic name, which can be copied from the Topic Management page in the console.![]() |
producer.py
.consumer.py
.#coding:utf8
from kafka import KafkaConsumer
consumer = KafkaConsumer(
'$topic_name',
group_id = "$group_id",
bootstrap_servers = ['$domainName:$port'],
api_version = (0,10,0)
)
for message in consumer:
print ("Topic:[%s] Partition:[%d] Offset:[%d] Value:[%s]" % (message.topic, message.partition, message.offset, message.value))
Parameter | Description |
---|---|
bootstrap_servers | Accessed network, which can be copied in the **Network** column in the Access Mode section on the instance details page in the console.![]() |
group_id | Consumer group ID, which can be customized according to the business needs |
topic_name | Topic name, which can be copied from the Topic Management page in the console.![]() |
consumer.py
.
Was this page helpful?