uvloop 是python圈子里近两年被抄的相当火热的高性能框架,uvloop是个高性能的异步非阻塞框架,他是完整的asyncio事件循环的替代品,建立在libuv基础之上,由Cython编写而成。Uvloop最终目的使得Asyncio更加快速。
根据我个人的测试结果分析uvloop性能确实要比gevent要高,但是易用性没有gevent来的舒服。python sanic也是基于uvloop实现的异步io,但总的来说uvloop的相关资料、实例都有些欠缺。
uvloop的服务端代码样例:
( 完整的样例代码, https://github.com/MagicStack/uvloop/tree/master/examples/bench )
# xiaorui.cc
async def echo_server(loop,address,unix):
if unix:
sock = socket(AF_UNIX,SOCK_STREAM)
else:
sock = socket(AF_INET,SOCK_STREAM)
sock.setsockopt(SOL_SOCKET,SO_REUSEADDR,1)
sock.bind(address)
sock.listen(5)
sock.setblocking(False)
if PRINT:
print('Server listening at',address)
with sock:
while True:
client,addr = await loop.sock_accept(sock) # 通过await来监听新连接
if PRINT:
print('Connection from',addr)
loop.create_task(echo_client(loop,client))
async def echo_client(loop,client):
try:
client.setsockopt(IPPROTO_TCP,TCP_NODELAY,1)
except (OSError,NameError):
pass
with client:
while True:
data = await loop.sock_recv(client,1000000) # 缓冲区有数据的监听唤醒
if not data:
break
await loop.sock_sendall(client,data)
if PRINT:
print('Connection closed')
async def echo_client_streams(reader,writer):
sock = writer.get_extra_info('socket')
try:
sock.setsockopt(IPPROTO_TCP,NameError):
pass
if PRINT:
print('Connection from',sock.getpeername())
while True:
data = await reader.read(1000000)
if not data:
break
writer.write(data)
if PRINT:
print('Connection closed')
writer.close()
import uvloop
uvloop.install()
loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)
loop.create_task(print_debug(loop))
coro = asyncio.start_unix_server(echo_client_streams, addr,loop=loop)
srv = loop.run_until_complete(coro)
loop.run_forever()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。