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


Posted in Python onApril 21, 2020

思路:

队列使用说明:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python使用PIL缩放网络图片并保存的方法
Apr 24 Python
简单讲解Python中的字符串与字符串的输入输出
Mar 13 Python
用Python写一个无界面的2048小游戏
May 24 Python
Python实现求解一元二次方程的方法示例
Jun 20 Python
python爬虫之线程池和进程池功能与用法详解
Aug 02 Python
python中将两组数据放在一起按照某一固定顺序shuffle的实例
Jul 15 Python
Python获取一个用户名的组ID过程解析
Sep 03 Python
selenium 多窗口切换的实现(windows)
Jan 18 Python
python实现控制台输出彩色字体
Apr 05 Python
Django用内置方法实现简单搜索功能的方法
Dec 18 Python
Python中Numpy和Matplotlib的基本使用指南
Nov 02 Python
Python实现双向链表
May 25 Python
安装多个版本的TensorFlow的方法步骤
Apr 21 #Python
解决Jupyter notebook中.py与.ipynb文件的import问题
Apr 21 #Python
TensorFLow 数学运算的示例代码
Apr 21 #Python
jupyter修改文件名方式(TensorFlow)
Apr 21 #Python
Python基于requests实现模拟上传文件
Apr 21 #Python
Ubuntu中配置TensorFlow使用环境的方法
Apr 21 #Python
基于jupyter代码无法在pycharm中运行的解决方法
Apr 21 #Python
You might like
PHP截取中文字符串的问题
2006/07/12 PHP
thinkphp常见路径用法分析
2014/12/02 PHP
[原创]PHPCMS遭遇会员投稿审核无效的解决方法
2017/01/11 PHP
PHP递归实现快速排序的方法示例
2017/12/18 PHP
Javascript添加监听与删除监听用法详解
2014/12/19 Javascript
javascript修改图片src的方法
2015/01/27 Javascript
js限制文本框的输入内容代码分享(3类)
2015/08/20 Javascript
jQuery实现div随意拖动的实例代码(通用代码)
2016/01/28 Javascript
jquery.qtip提示信息插件用法简单实例
2016/06/17 Javascript
webuploader模态框ueditor显示问题解决方法
2016/12/27 Javascript
jQuery实现锚点向下平滑滚动特效示例
2017/08/29 jQuery
微信小程序实现图片放大预览功能
2020/10/22 Javascript
详解iview的checkbox多选框全选时校验问题
2019/06/10 Javascript
NodeJS实现一个聊天室功能
2019/11/25 NodeJs
小程序跳转到的H5页面再跳转回跳小程序的方法
2020/03/06 Javascript
VueX模块的具体使用(小白教程)
2020/06/05 Javascript
Python二维码生成库qrcode安装和使用示例
2014/12/16 Python
python正则表达式去除两个特殊字符间的内容方法
2018/12/24 Python
Django给admin添加Action的步骤详解
2019/05/01 Python
python下的opencv画矩形和文字注释的实现方法
2019/07/09 Python
python新手学习可变和不可变对象
2020/06/11 Python
Crabtree & Evelyn欧盟:豪华洗浴、身体和护发
2021/03/09 全球购物
Oasis服装官网:时尚女装在线
2020/07/09 全球购物
老师自我鉴定范文
2013/12/25 职场文书
酒店经理职责
2014/01/30 职场文书
环保倡议书500字
2014/05/15 职场文书
低碳生活的宣传标语
2014/06/23 职场文书
大学学生个人总结
2015/02/15 职场文书
单位更名证明
2015/06/18 职场文书
离婚民事起诉状
2015/08/03 职场文书
2016年寒假学习心得体会
2015/10/09 职场文书
2016年庆祝六一儿童节活动总结
2016/04/06 职场文书
Golang生成Excel文档的方法步骤
2021/06/09 Golang
关于@OnetoMany关系映射的排序问题,使用注解@OrderBy
2021/12/06 Java/Android
一条慢SQL语句引发的改造之路
2022/03/16 MySQL
windows server2008 开启端口的实现方法
2022/06/25 Servers