1. 程式人生 > 程式設計 >Python多執行緒實現支付模擬請求過程解析

Python多執行緒實現支付模擬請求過程解析

思路:

  佇列使用說明:

  •    multiprocessing.Queue()#用於程序間通訊,單主程序與子程序無法通訊(使用程序池時儘量不要使用這個)
  •    multiprocessing.Manager().Queue()#用於主子程序通訊,通過程序池(pool)建立的程序可以資料共享
  •    queue.Queue()#用於執行緒間通訊,同一程序內的資料可以共享

  1.從資料庫裡獲取待支付的訂單

  2.將獲取出來的資料新增至佇列(queue.Queue()),並在函式中返回訊息佇列的長度

  3.根據佇列長度建立對應的執行緒數量

  4.把建立的執行緒放在list

  5.依次啟動

  6.最後等待主執行緒執行完結束,統計函式執行時長

程式碼如下

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 #查詢記錄條數
    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#驗證token有效性
  def get_fwh_token_list(self):
    token_list=self.fwh_token.loadTokenList()
    return token_list

  @token_crm#驗證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" #檔案首行資料
      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,encoding='utf-8') as file2:#檔案寫入
          str_DoWeChatNotifyInfo=str(fwh_order_id)+'\t'+str(fwh_order_sn)+'\t\n'
          file2.flush() #清除緩衝區
          file2.write(str_DoWeChatNotifyInfo)
        self.que.put(self.fwh_order_dict)#將資料新增至佇列
    #關閉資料庫連線
    # self.my_op.close_db_fwh()
    # self.my_op.close_db()
    return self.que.qsize()#返回佇列數量

  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 '訂單狀態錯誤,非待支付訂單' in response_wechat_success_huidiao['msg']:
        print(data_wechat_success_huidiao)
    else:
      print('待支付訂單為空')

  def run_multithreading(self):#多執行緒
    threads = []#存放所有的執行緒
    nloops = list(range(self.testDoWeChatNotify()))#獲取佇列數量
    if len(nloops)>0:
      for i,k in zip(nloops,self.que.get().items()):#根據佇列數量來建立執行緒
        t = Thread(target=self.asynchronousPay,args=(k[0],k[1]))
        threads.append(t)

      for s in nloops: # 開始多執行緒
        threads[s].start()

      for j in nloops: # 等待所有執行緒完成
        threads[j].join()
    else:
      print("佇列數量為空")

if __name__=="__main__":
  start_time = time.time() # 計算程式開始時間
  wechfy=doWeChatNotify()
  wechfy.run_multithreading()#多執行緒
  print('程式耗時{:.2f}'.format(time.time() - start_time)) # 計算程式總耗時

總結:親測執行時間還是會快很多,單執行緒支付100個訂單四十幾秒的樣子,多執行緒執行不用join2.x秒,用join八秒的樣子,還有很大的優化空間,因為執行時會建立100個執行緒

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。