Python多線程實(shí)現(xiàn)支付模擬請(qǐng)求過(guò)程解析
思路:
隊(duì)列使用說(shuō)明:
- multiprocessing.Queue()#用于進(jìn)程間通信,單主進(jìn)程與子進(jìn)程無(wú)法通信(使用進(jìn)程池時(shí)盡量不要使用這個(gè))
- multiprocessing.Manager().Queue()#用于主子進(jìn)程通信,通過(guò)進(jìn)程池(pool)創(chuàng)建的進(jìn)程可以數(shù)據(jù)共享
- queue.Queue()#用于線程間通信,同一進(jìn)程內(nèi)的數(shù)據(jù)可以共享
1.從數(shù)據(jù)庫(kù)里獲取待支付的訂單
2.將獲取出來(lái)的數(shù)據(jù)添加至隊(duì)列(queue.Queue()),并在函數(shù)中返回消息隊(duì)列的長(zhǎng)度
3.根據(jù)隊(duì)列長(zhǎng)度創(chuàng)建對(duì)應(yīng)的線程數(shù)量
4.把創(chuàng)建的線程放在list
5.依次啟動(dòng)
6.最后等待主線程執(zhí)行完結(jié)束,統(tǒng)計(jì)函數(shù)運(yùn)行時(shí)長(zhǎng)
代碼如下
import asyncio import sys from queue import Queue sys.path.append("../") from tool.__init__ import * from tool.decorator_token import * import time from threading import Thread,Lock class doWeChatNotify(BaseTest): def __init__(self): super().__init__() self.limit_num=100 #查詢記錄條數(shù) self.WeChatNotify_sql='''select order_id,order_sn from fw_order where `status`=0 and course_id=1569 ORDER BY create_time desc limit %d ;'''%(self.limit_num) self.fwh_test_api=fwh_test_api self.data = self.my_op.sql_operation_fwh(self.WeChatNotify_sql) self.fwh_order_dict = {} self.que = Queue() @token_fwh#驗(yàn)證token有效性 def get_fwh_token_list(self): token_list=self.fwh_token.loadTokenList() return token_list @token_crm#驗(yàn)證token有 def get_crm_token_list(self) token_list=self.token.loadTokenList() return token_list def testDoWeChatNotify(self): DoWeChatNotify_file='../tokenFileAndtxtFiles'+'/'+"DoWeChatNotify_asynchronousPay.txt" with open(DoWeChatNotify_file,'a',encoding='utf=-8') as file: str_first="order_id\t"+"order_sn\t\n" #文件首行數(shù)據(jù) file.write(str_first) fwh_order_id_list, fwh_order_sn_list = [], [] if self.data!=(): for a in self.data: fwh_order_id=a['order_id'] fwh_order_sn=a['order_sn'] self.fwh_order_dict[fwh_order_id]=fwh_order_sn with open(DoWeChatNotify_file,'a',encoding='utf-8') as file2:#文件寫(xiě)入 str_DoWeChatNotifyInfo=str(fwh_order_id)+'\t'+str(fwh_order_sn)+'\t\n' file2.flush() #清除緩沖區(qū) file2.write(str_DoWeChatNotifyInfo) self.que.put(self.fwh_order_dict)#將數(shù)據(jù)添加至隊(duì)列 #關(guān)閉數(shù)據(jù)庫(kù)連接 # self.my_op.close_db_fwh() # self.my_op.close_db() return self.que.qsize()#返回隊(duì)列數(shù)量 def asynchronousPay(self,order_id,order_sn): count=1 count_num=50 token_list=self.get_fwh_token_list() if (self.data!=()): headers_form_urlencoded['token']=token_list[0] url_wechat_success_huidiao=self.fwh_test_api+'/index/Order/doWeChatNotify' data_wechat_success_huidiao=self.data_to_str.requestDataToStr_firefoxAndChrome_fwh('''order_sn:{} order_id:{} meth_id:4 timestamp:157129653969 sign:0687b01b300b9e300d3996a9d2173f1380973e5a'''.format(order_sn,order_id)) request_wechat_success_huidiao=requests.post(url=url_wechat_success_huidiao,headers=headers_form_urlencoded,data=data_wechat_success_huidiao) response_wechat_success_huidiao=request_wechat_success_huidiao.json() if '訂單狀態(tài)錯(cuò)誤,非待支付訂單' in response_wechat_success_huidiao['msg']: print(data_wechat_success_huidiao) else: print('待支付訂單為空') def run_multithreading(self):#多線程 threads = []#存放所有的線程 nloops = list(range(self.testDoWeChatNotify()))#獲取隊(duì)列數(shù)量 if len(nloops)>0: for i,k in zip(nloops,self.que.get().items()):#根據(jù)隊(duì)列數(shù)量來(lái)創(chuàng)建線程 t = Thread(target=self.asynchronousPay,args=(k[0],k[1])) threads.append(t) for s in nloops: # 開(kāi)始多線程 threads[s].start() for j in nloops: # 等待所有線程完成 threads[j].join() else: print("隊(duì)列數(shù)量為空") if __name__=="__main__": start_time = time.time() # 計(jì)算程序開(kāi)始時(shí)間 wechfy=doWeChatNotify() wechfy.run_multithreading()#多線程 print('程序耗時(shí){:.2f}'.format(time.time() - start_time)) # 計(jì)算程序總耗時(shí)
總結(jié):親測(cè)運(yùn)行時(shí)間還是會(huì)快很多,單線程支付100個(gè)訂單四十幾秒的樣子,多線程運(yùn)行不用join2.x秒,用join八秒的樣子,還有很大的優(yōu)化空間,因?yàn)檫\(yùn)行時(shí)會(huì)創(chuàng)建100個(gè)線程
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python入門(mén)教程 超詳細(xì)1小時(shí)學(xué)會(huì)Python
本文適合有經(jīng)驗(yàn)的程序員盡快進(jìn)入Python世界.特別地,如果你掌握J(rèn)ava和Javascript,不用1小時(shí)你就可以用Python快速流暢地寫(xiě)有用的Python程序.2006-09-09Python爬蟲(chóng)使用Selenium+PhantomJS抓取Ajax和動(dòng)態(tài)HTML內(nèi)容
這篇文章主要介紹了Python爬蟲(chóng)使用Selenium+PhantomJS抓取Ajax和動(dòng)態(tài)HTML內(nèi)容,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02Python實(shí)現(xiàn)簡(jiǎn)單文本字符串處理的方法
這篇文章主要介紹了Python實(shí)現(xiàn)簡(jiǎn)單文本字符串處理的方法,涉及Python針對(duì)文本字符串的切割、計(jì)算、轉(zhuǎn)換等相關(guān)操作技巧,需要的朋友可以參考下2018-01-01Python統(tǒng)計(jì)節(jié)假日剩余天數(shù)的腳本
過(guò)完春節(jié),盼著下一個(gè)節(jié)日,那么如何判斷距離節(jié)假日還有多少天呢?今天小編給大家介紹使用python腳本來(lái)解決這個(gè)問(wèn)題,對(duì)Python統(tǒng)計(jì)節(jié)假日倒計(jì)時(shí)腳本感興趣的朋友一起看看吧2022-02-02python實(shí)現(xiàn)列車管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)列車管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09django數(shù)據(jù)庫(kù)migrate失敗的解決方法解析
這篇文章主要介紹了django數(shù)據(jù)庫(kù)migrate失敗的解決方法解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-02-02pytorch中retain_graph==True的作用說(shuō)明
這篇文章主要介紹了pytorch中retain_graph==True的作用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02