python串連kafka生產者,消費者指令碼

來源:互聯網
上載者:User

標籤:sum   params   time   produce   1.2   false   board   boot   sleep   

# -*- coding: utf-8 -*-‘‘‘‘‘    使用kafka-Python 1.3.3模組    # pip install kafka==1.3.5    # pip install kafka-python==1.3.5‘‘‘import sysimport timeimport jsonfrom kafka import KafkaProducerfrom kafka import KafkaConsumerfrom kafka.errors import KafkaErrorKAFAKA_HOST = "101.236.51.235"KAFAKA_PORT = 9092KAFAKA_TOPIC = "test"class Kafka_producer():    ‘‘‘‘‘    生產模組:根據不同的key,區分訊息    ‘‘‘    def __init__(self, kafkahost,kafkaport, kafkatopic, key):        self.kafkaHost = kafkahost        self.kafkaPort = kafkaport        self.kafkatopic = kafkatopic        self.key = key        print("producer:h,p,t,k",kafkahost,kafkaport,kafkatopic,key)        bootstrap_servers = ‘{kafka_host}:{kafka_port}‘.format(                kafka_host=self.kafkaHost,                kafka_port=self.kafkaPort                )        print("boot svr:",bootstrap_servers)        self.producer = KafkaProducer(bootstrap_servers = bootstrap_servers                )    def sendjsondata(self, params):        try:            parmas_message = json.dumps(params,ensure_ascii=False)            producer = self.producer            print(parmas_message)            v = parmas_message.encode(‘utf-8‘)            k = key.encode(‘utf-8‘)            print("send msg:(k,v)",k,v)            producer.send(self.kafkatopic, key=k, value= v)            producer.flush()        except KafkaError as e:            print (e)class Kafka_consumer():    ‘‘‘‘‘    消費模組: 通過不同groupid消費topic裡面的訊息    ‘‘‘    def __init__(self, kafkahost, kafkaport, kafkatopic, groupid):        self.kafkaHost = kafkahost        self.kafkaPort = kafkaport        self.kafkatopic = kafkatopic        self.groupid = groupid        self.key = key        self.consumer = KafkaConsumer(self.kafkatopic, group_id = self.groupid,                bootstrap_servers = ‘{kafka_host}:{kafka_port}‘.format(                    kafka_host=self.kafkaHost,                    kafka_port=self.kafkaPort )                )    def consume_data(self):        try:            for message in self.consumer:                yield message        except KeyboardInterrupt as e:            print (e)def main(xtype, group, key):    ‘‘‘‘‘    測試consumer和producer    ‘‘‘    if xtype == "p":        # 生產模組        producer = Kafka_producer(KAFAKA_HOST, KAFAKA_PORT, KAFAKA_TOPIC, key)        print ("===========> producer:", producer)        for _id in range(100):           params = ‘{"msg" : "%s"}‘ % str(_id)           params=[{"msg0" :_id},{"msg1" :_id}]           producer.sendjsondata(params)           time.sleep(1)    if xtype == ‘c‘:        # 消費模組        consumer = Kafka_consumer(KAFAKA_HOST, KAFAKA_PORT, KAFAKA_TOPIC, group)        print ("===========> consumer:", consumer)        message = consumer.consume_data()        for msg in message:            print (‘msg---------------->k,v‘, msg.key,msg.value)            print (‘offset---------------->‘, msg.offset)if __name__ == ‘__main__‘:    xtype = sys.argv[1]    group = sys.argv[2]    key = sys.argv[3]    main(xtype, group, key)

使用方式
生產訊息

python testkafka.py p g k
消費訊息

python testkafka.py c g k

python串連kafka生產者,消費者指令碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.