python uvloop异步框架学习

uvloop 是python圈子里近两年被抄的相当火热的高性能框架,uvloop是个高性能的异步非阻塞框架,他是完整的asyncio事件循环的替代品,建立在libuv基础之上,由Cython编写而成。Uvloop最终目的使得Asyncio更加快速。   

根据我个人的测试结果分析uvloop性能确实要比gevent要高,但是易用性没有gevent来的舒服。python sanic也是基于uvloop实现的异步io,但总的来说uvloop的相关资料、实例都有些欠缺。


uvloop 网络编程的一些介绍:

https://www.youtube.com/watch?v=WSq0S7UvI8E&t=33s

再贴一个 sanic的地址.   https://github.com/channelcat/sanic


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, TCP_NODELAY, 1)
    except (OSError, 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
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()

对于 uvloop 的一些详细用法后面再说.


大家觉得文章对你有些作用! 如果想赏钱,可以用微信扫描下面的二维码,感谢!
另外再次标注博客原地址  xiaorui.cc

发表评论

电子邮件地址不会被公开。 必填项已用*标注