Python測試Kafka叢集(pykafka)

右介發表於2017-11-14

生產者程式碼:

# -* coding:utf8 *-  
from pykafka import KafkaClient  
  
host = 'IP:9092, IP:9092, IP:9092'
client = KafkaClient(hosts = host)  
  
print client.topics  
  
# 生產者  
topicdocu = client.topics['my-topic']  
producer = topicdocu.get_producer()  
for i in range(100):  
    print i  
    producer.produce('test message ' + str(i ** 2))  
producer.stop()

消費者程式碼:

# -* coding:utf8 *-  
from pykafka import KafkaClient  
  
host = 'IP:9092, IP:9092, IP:9092'
client = KafkaClient(hosts = host)  
  
print client.topics  
  
# 消費者  
topic = client.topics['my-topic']  
consumer = topic.get_simple_consumer(consumer_group='test', auto_commit_enable=True, auto_commit_interval_ms=1,  
                                     consumer_id='test')  
for message in consumer:  
    if message is not None:  
        print message.offset, message.value  

 

相關文章