Kafka-3python producers and Consumers practical demo

Source: Internet
Author: User
Tags server port

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.