Python多线程实现支付模拟请求过程解析

作者:yaominghui 时间:2023-04-09 17:59:35 

思路:

队列使用说明:

  • 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,'a',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个线程

来源:https://www.cnblogs.com/qtclm/p/12116250.html

标签:python,多,线程,支付
0
投稿

猜你喜欢

  • 设计师的职业规划

    2009-08-31 12:52:00
  • Python批量解压&压缩文件夹的示例代码

    2023-02-17 17:43:29
  • Python实现的石头剪子布代码分享

    2023-04-11 09:14:58
  • MySQL查询出现1055错误的原因及解决方法

    2024-01-13 04:05:54
  • Python编程技巧连接列表的八种操作方法

    2022-02-10 02:08:54
  • SQL对时间处理的语句小结

    2011-12-01 07:53:04
  • Python执行时间的几种计算方法

    2023-06-09 15:00:47
  • php ajax无刷新上传图片实例代码

    2024-04-17 10:40:02
  • python自动化测试selenium执行js脚本实现示例

    2023-10-23 06:41:58
  • 仿DW的图形菜单 DIV+CSS

    2007-08-14 10:07:00
  • python下如何查询CS反恐精英的服务器信息

    2021-09-15 05:51:47
  • MySQL8.0.20单机多实例部署步骤

    2024-01-13 13:46:37
  • Mysql中二进制日志操作方法说明

    2024-01-25 23:08:28
  • asp如何计算下载一个文件需要多长时间?

    2009-11-25 20:17:00
  • 使用Keras中的ImageDataGenerator进行批次读图方式

    2023-07-02 03:49:50
  • SQLServer用存储过程实现插入更新数据示例

    2024-01-27 23:48:05
  • javascript实现rgb颜色转换成16进制格式

    2024-04-18 09:33:58
  • 前端使用svg图片改色实现示例

    2022-03-14 03:54:14
  • Mysql案例刨析事务隔离级别

    2024-01-14 00:35:47
  • Python matplotlib画曲线例题解析

    2022-10-18 14:17:30
  • asp之家 网络编程 m.aspxhome.com