日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python3連接kafka模塊pykafka生產(chǎn)者簡單封裝

系統(tǒng) 1762 0

1.1安裝模塊

            
              pip install pykafka

            
          

1.2基本使用

            
              # -* coding:utf8 *-  
from pykafka import KafkaClient  
host = 'IP:9092, IP:9092, IP:9092'
client = KafkaClient(hosts = host)  
# 生產(chǎn)者  
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()

            
          

1.3簡單封裝

            
              class KafkaProduct():

    def __init__(self,hosts,topic):
        """
        初始化實(shí)例
        :param hosts: 連接地址
        :param topic:
        """
        self.__client = KafkaClient(hosts=hosts)
        self.__topic = self.__client.topics[topic.encode()]

    def __set_topic(self, topic):
        self.__topic = self.__client.topics[topic.encode()]

    def set_topic(self, topic):
        """
        設(shè)置topic
        :param topic:
        :return:
        """
        self.__set_topic(topic)

    def get_topics(self):
        """
        獲取當(dāng)前所有topic
        :return:
        """
        return self.__client.topics

    def get_topic(self):
        """
        獲取當(dāng)前topic
        :return:
        """
        return self.__topic

    def Producer(self):
        """
        生產(chǎn)者對象
        :return:
        """
        with self.__topic.get_producer(delivery_reports=True) as producer:
            next_data = ''
            while True:
                if next_data:
                    producer.produce(str(next_data).encode())
                next_data = yield True

    def send_data(self,datas):
        """
        發(fā)送數(shù)據(jù)
        :param datas:需要傳入的可迭代對象
        :return:
        """
        c = self.Producer()
        next(c)
        for i in datas:
            c.send(i)

if __name__ == '__main__':

hosts = "1.2.3.4:9999,2.3.4.5:9090" #連接hosts
topic = "test_523"
K = KafkaProduct(hosts=hosts, topic=topic)  #
#K.set_topic("test")  #切換設(shè)置新的topic
K.get_topic()  #獲取當(dāng)前設(shè)置的topic
#K.get_topics() #獲取所有topic
data = range(10000)  #要發(fā)送的可迭代對象
K.send_data(data)

            
          

1.4引用來源

博客園:Python測試Kafka集群(pykafka)

知乎:使用生成器把Kafka寫入效率提高1000倍


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 肇州县| 三原县| 大名县| 太湖县| 黄浦区| 孟州市| 洛宁县| 五莲县| 舞阳县| 濮阳市| 黔南| 达日县| 巫山县| 祥云县| 莱阳市| 金山区| 饶平县| 本溪市| 壶关县| 山西省| 乌苏市| 新泰市| 嘉禾县| 老河口市| 都江堰市| 关岭| 曲沃县| 安徽省| 合山市| 绥江县| 固始县| 双牌县| 武定县| 洛扎县| 福泉市| 陆川县| 余江县| 永济市| 洛隆县| 宜城市| 葵青区|