官方文檔:https://kafka-python.readthedocs.io/en/master/apidoc/KafkaConsumer.html
目前成都創(chuàng)新互聯(lián)公司已為成百上千的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬主機(jī)、網(wǎng)站托管、企業(yè)網(wǎng)站設(shè)計(jì)、江西網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。import threading import os import sys from kafka import KafkaConsumer, TopicPartition, OffsetAndMetadata from consumers.db_util import * from consumers.json_dispose import * from collections import OrderedDict threads = [] # col_dic, sql_dic = get() class MyThread(threading.Thread): def __init__(self, thread_name, topic, partition): threading.Thread.__init__(self) self.thread_name = thread_name # self.keyName = keyName self.partition = partition self.topic = topic def run(self): print("Starting " + self.name) Consumer(self.thread_name, self.topic, self.partition) def stop(self): sys.exit() def Consumer(thread_name, topic, partition): broker_list = '172.16.90.63:6667, 172.16.90.58:6667, 172.16.90.59:6667' ''' fetch_min_bytes(int) - 服務(wù)器為獲取請(qǐng)求而返回的最小數(shù)據(jù)量,否則請(qǐng)等待 fetch_max_wait_ms(int) - 如果沒有足夠的數(shù)據(jù)立即滿足fetch_min_bytes給出的要求,服務(wù)器在回應(yīng)提取請(qǐng)求之前將阻塞的大時(shí)間量(以毫秒為單位) fetch_max_bytes(int) - 服務(wù)器應(yīng)為獲取請(qǐng)求返回的大數(shù)據(jù)量。這不是絕對(duì)大值,如果獲取的第一個(gè)非空分區(qū)中的第一條消息大于此值, 則仍將返回消息以確保消費(fèi)者可以取得進(jìn)展。注意:使用者并行執(zhí)行對(duì)多個(gè)代理的提取,因此內(nèi)存使用將取決于包含該主題分區(qū)的代理的數(shù)量。 支持的Kafka版本> = 0.10.1.0。默認(rèn)值:52428800(50 MB)。 enable_auto_commit(bool) - 如果為True,則消費(fèi)者的偏移量將在后臺(tái)定期提交。默認(rèn)值:True。 max_poll_records(int) - 單次調(diào)用中返回的大記錄數(shù)poll()。默認(rèn)值:500 max_poll_interval_ms(int) - poll()使用使用者組管理時(shí)的調(diào)用之間的大延遲 。這為消費(fèi)者在獲取更多記錄之前可以閑置的時(shí)間量設(shè)置了上限。 如果 poll()在此超時(shí)到期之前未調(diào)用,則認(rèn)為使用者失敗,并且該組將重新平衡以便將分區(qū)重新分配給另一個(gè)成員。默認(rèn)300000 ''' consumer = KafkaConsumer(bootstrap_servers=broker_list, group_id="xiaofesi", client_id=thread_name, enable_auto_commit=False, fetch_min_bytes=1024*1024,#1M # fetch_max_bytes=1024 * 1024 * 1024 * 10, fetch_max_wait_ms=60000,#30s request_timeout_ms=305000, # consumer_timeout_ms=1, # max_poll_records=5000, # max_poll_interval_ms=60000 無該參數(shù) ) #查出數(shù)據(jù)庫上次保存的offset,此offset已經(jīng)是上次消費(fèi)最后一條的offset的offset+1,也就是這次消費(fèi)的起始位 dic = get_kafka(topic, partition) tp = TopicPartition(topic, partition) print(thread_name, tp, dic['offset']) #分配該消費(fèi)者的TopicPartition,也就是topic和partition,根據(jù)參數(shù),我是三個(gè)消費(fèi)者,三個(gè)線程,每個(gè)線程消費(fèi)者消費(fèi)一個(gè)分區(qū) consumer.assign([tp]) #重置此消費(fèi)者消費(fèi)的起始位 consumer.seek(tp, dic['offset']) print("程序首次運(yùn)行\(zhòng)t線程:", thread_name, "分區(qū):", partition, "偏移量:", dic['offset'], "\t開始消費(fèi)...") num=0 #記錄該消費(fèi)者消費(fèi)次數(shù) # end_offset = consumer.end_offsets([tp])[tp] # print(end_offset) while True: args = OrderedDict() msg = consumer.poll(timeout_ms=60000) end_offset = consumer.end_offsets([tp])[tp] print('已保存的偏移量', consumer.committed(tp),'最新偏移量,',end_offset) if len(msg) > 0: print("線程:", thread_name, "分區(qū):", partition, "大偏移量:", end_offset, "有無數(shù)據(jù),", len(msg)) lines=0 for data in msg.values(): for line in data: lines+=1 line = eval(line.value.decode('utf-8')) ''' do something ''' # 線程此批次消息條數(shù) print(thread_name,"lines",lines) #數(shù)據(jù)保存至數(shù)據(jù)庫 is_succeed = save_to_db(args, thread_name) if is_succeed: #更新自己保存在數(shù)據(jù)庫中的各topic, partition的偏移量 is_succeed1 = update_offset(topic, partition, end_offset) #手動(dòng)提交偏移量 offsets格式:{TopicPartition:OffsetAndMetadata(offset_num,None)} consumer.commit(offsets={tp:(OffsetAndMetadata(end_offset,None))}) print(thread_name,"to db suss",num+1) if is_succeed1 == 0: #系統(tǒng)退出?這個(gè)還沒試 os.exit() ''' sys.exit() 只能退出該線程,也就是說其它兩個(gè)線程正常運(yùn)行,主程序不退出 ''' else: os.exit() else: print(thread_name,'沒有數(shù)據(jù)') num+=1 print(thread_name,"第",num,"次") if __name__ == '__main__': try: t1 = MyThread("Thread-0", "test", 0) threads.append(t1) t2 = MyThread("Thread-1", "test", 1) threads.append(t2) t3 = MyThread("Thread-2", "test", 2) threads.append(t3) for t in threads: t.start() for t in threads: t.join() print("exit program with 0") except: print("Error: failed to run consumer program")
文章題目:pythonkafka多線程消費(fèi)者&手動(dòng)提交實(shí)例-創(chuàng)新互聯(lián)
標(biāo)題URL:http://www.rwnh.cn/article14/cssgde.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)頁設(shè)計(jì)公司、品牌網(wǎng)站建設(shè)、營銷型網(wǎng)站建設(shè)、網(wǎng)站制作、App設(shè)計(jì)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容