The program is divided into productor.py is the sending message end, consumer for the consumer message end,
Start product before starting the consumer, after all, only send a message, the consumer has the message can be consumed,
productor.py
#!/usr/bin/env python2.7#_*_coding:utf-8 _*_from Kafka Import kafkaproducerkafka_host = ' 192.168.1.200 ' # Kafka server address Kaf Ka_port = 9092 # Kafka server Port producer = Kafkaproducer (bootstrap_servers=[' {kafka_host}:{kafka_port} '. Format (kafka_hos t = kafka_host, Kafka_port = kafka_port)]) #简单for循环10次, sends 10 messages for I in range (1,10): message_string = ' some message '. f Ormat (i) #调用send方法, send the TopicID with the name ' Topic1 ', send the message for message_string response = producer.send (' Topic1 ', Message_string.enc Ode (' Utf-8 ')) print response
consumer.py
#!/usr/bin/env python#_*_coding:utf-8 _*_import jsonfrom Kafka Import *kafka_host = ' 192.168.1.200 ' # Kafka server address Kafka_po RT = 9092 # Kafka Server Port # consume Topic1 topic and specify GROUP_ID (custom), multiple machines or processes want to order consumption, can specify the same group_id,# if you want to spend more than one consumption, you can change a group_id, will be consumed from the beginning consumer = Kafkaconsumer (' Topic1 ', group_id = ' My-group ', bootstrap_servers = [' {kafka_host}:{kafka_port} '. Format (Kafka_host=kafka_host, Kafka_port=kafka_port)]) for message in consumer: #json读取kafka的消息 content = Json.load S (message.value) print content
This article is from the "Ma Pengfei--" blog, please be sure to keep this source http://mapengfei.blog.51cto.com/1552412/1926068
Kafka-3python producers and Consumers practical demo