python3.x 多路IO复用补充asyncio
2024-09-08 04:46:21
asyncio模块是python之父写的模块,按说应该是靠谱的,python3.6版本定义为稳定版本。
说明书:https://docs.python.org/3/library/asyncio.html?highlight=asyncio#module-asyncio
大概定义:该模块提供了使用协程编写单线程并发代码,通过套接字和其他资源复用I / O访问,运行网络客户端和服务器以及其他相关原语的基础结构。
简单应用(基于wsgi的报警器)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/8/21 10:40
# @Author : WangYue
# @Site :
# @File : alertor_uwsgi.py
# @Software: PyCharm #加入环境变量避免程序报错
import sys,os
sys.path.append(os.path.dirname(os.path.dirname(__file__))) #引入wsgi模型,这里主要是弄一个简单的http模型来说明asyncio的简单使用
from wsgiref.simple_server import make_server #引入asyncio
import asyncio #引入其他可能的依赖
from threading import Thread
import json #引入本程序其他的内容,与asyncio无关是程序业务的其他部分
from conf.alertor_conf import ALERTOR_CONFIG
from model.alert_method_class import SendMail #定义一个运行asyncio loop 的线程,去单独运行它
def start_loop(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
new_loop = asyncio.new_event_loop() #这个new_loop将会用于运行异步程序
t = Thread(target=start_loop, args=(new_loop,))
t.start() #利用多线程,额外起一个线程运行asyncio loop然后它在自身使用协程之类处异步处理业务 #这是wsgi主业务程序,application是wsgi的入口程序,wsgi就规定了这么个函数名,这样写wsgi就认可它是入口了。传参也是wsgi的规定,第一个是环境,第二个是响应
def application(env,start_res):
res_headers=[('Content-type', 'text/plain')]
if env["REQUEST_METHOD"]=='POST':
# the environment variable CONTENT_LENGTH may be empty or missing
try:
if env['PATH_INFO'] != "/send_alert":
status = "404 func is not in use"
start_res(status, res_headers)
return [b"func is not in use"] request_body_size = int(env.get('CONTENT_LENGTH', 0))
status = "200 OK"
request_body = env['wsgi.input'].read(request_body_size)
print("post_info -->", request_body.decode())
r_body=json.loads(request_body.decode())
#就这里一行代码,new_loop.call_soon_threadsafe(),告诉asyncio去运行第一个参数的函数名,后边的参数是被运行函数的传参,有多少就传参多少个,这是异步的,非阻塞的。
new_loop.call_soon_threadsafe(SendMail.sendEmail,"Alertor Alarm level:"+r_body["level"]+" server: "+r_body["server"],r_body)
start_res(status,res_headers)
return [b"ok send alert......."]
except (ValueError):
status = "404 json data not found key"
request_body_size = 0
start_res(status, res_headers)
return [b"get post info faild"] else:
status = "403 method error"
start_res(status,res_headers)
return [b'method error'] # 1、只接受POST请求。数据为json格式,json中标记的,包括但不限于,包括的信息将会入库,其他信息,在告警时会一并发出
# {
# "level":"high", #告警级别,"high","medium","info",这个可以在配置文件中配置,配置信息是个列表,有序的从左至右为["high","medium","info"],对应后续告警逻辑及post中json的本字段。
# "@timestamp":"",#告警时间
# "server":"",#告警源,可以是ip,主机名,服务名等可标识的
# "message":""#具体的告警信息
# }
# 2、根据json中的level自动选择告警途径,选择方式,在配置文件中的alert_method字典信息
# 3、将告警内容,存储数据库,便于日后查询
# 4、后续提供查询统计告警信息的方法 if __name__=="__main__":
wsgi_server=make_server(ALERTOR_CONFIG['bind_ip'],ALERTOR_CONFIG['port'],application) wsgi_server.serve_forever()
目前这里先这么用,这个模型的性能是基于uwsgi运行,2进程,每个进程内4个线程,基准性能是15000请求总量,5000客户端
ab -n 15000-c 5000 -p test_alert.txt -T application/x-www-form-urlencoded "http://test.alert.com.cn/test.html"
效果还凑合吧。
最新文章
- Windows 7 常用快捷键
- URI 中特殊字符处理
- 插入备份数据 报 IDENTITY_INSERT 为 ON 时解决方法
- 简明python教程 --C++程序员的视角(一):数值类型、字符串、运算符和控制流
- [转]Sublime Text3注册码(可用)
- thinkphp隐藏中url的index.php
- 二:ZooKeeper术语概念
- FileZilla Server 防火墙端口开启设置 windows 2008 win
- Android 软件盘 动态设置 layout
- .NET进阶系列之一:C#正则表达式整理备忘
- css3-多列显示文字
- 说下browserslist
- Kotlin入门(31)JSON字符串的解析
- 【UVA1660】Cable TV Network
- xml方式封装数据方法
- Delphi7使用一段时间后抽风提示注册
- 10-SQL Server 2008 R2安装步骤
- mysql+redis
- 静态HTML总结
- Win10+Ubuntu1604双系统
热门文章
- MQ简介1
- iOS开发 - 线程与进程的认识与理解
- GYM 101889B(找规律)
- bzoj 4695: 最假女选手 &;&; Gorgeous Sequence HDU - 5306 &;&; (bzoj5312 冒险 || 小B的序列) &;&; bzoj4355: Play with sequence
- axios delete 请求
- json数据有换行符时提交不成功的坑
- QQ免费企业邮箱申请配置
- sgu316Kalevich Strikes Back(线段树+扫描线)
- Flask 学习系列(二)---Jinjia2模板
- Java 多个if 和多个else if 的区别