asyncpg - 连接与连接池

时间:2017-02-15 06:25:34

标签: python

我正在查看asyncpg的文档,我无法理解为什么使用连接池而不是单个连接。

example given中,使用了一个池:

async with pool.acquire() as connection:
    async with connection.transaction():
        result = await connection.fetchval('select 2 ^ $1', power)
        return web.Response(
            text="2 ^ {} is {}".format(power, result))

但也可以通过在必要时创建连接来完成:

connection = await asyncpg.connect(user='postgres')
async with connection.transaction():
    result = await connection.fetchval('select 2 ^ $1', power)
    return web.Response(
            text="2 ^ {} is {}".format(power, result))

根据需要使用池而不是连接有什么好处?

2 个答案:

答案 0 :(得分:12)

建立与数据库服务器的连接是一项昂贵的操作。连接池是一种常见的技术,可以避免支付这笔费用。游泳池保持连接打开,并在必要时将其出租。

通过简单的基准测试很容易看到游泳池的好处:

async def bench_asyncpg_con():
    power = 2
    start = time.monotonic()
    for i in range(1, 1000):
        con = await asyncpg.connect(user='postgres', host='127.0.0.1')
        await con.fetchval('select 2 ^ $1', power)
        await con.close()

    end = time.monotonic()
    print(end - start)

上述操作在1.568秒内在我的机器上完成。

而池版本:

async def bench_asyncpg_pool():
    pool = await asyncpg.create_pool(user='postgres', host='127.0.0.1')
    power = 2
    start = time.monotonic()
    for i in range(1, 1000):
        async with pool.acquire() as con:
            await con.fetchval('select 2 ^ $1', power)

    await pool.close()
    end = time.monotonic()
    print(end - start)

运行0.234秒,或 6.7倍

答案 1 :(得分:0)

猫王Pranskevichus 显示了上述两个基准。我拿了第一个bench_asyncpg_con并进行了编辑,将con移到了循环之外:

async def bench_asyncpg_con_2():
    power = 2
    start = time.monotonic()
    con = await asyncpg.connect(**data)
    for i in range(1, 1000):
        await con.fetchval('select 2 ^ $1', power)

    await con.close()
    end = time.monotonic()
    print(end - start) 

这比bench_asyncpg_pool

快得多

我对此有0.45,而我

1.62bench_asyncpg_pool

63.18 on bench_asyncpg_con

我是一个使用这个lib的新手,并认为整个项目的一个连接con是一个不错的选择。如我错了请纠正我。我会感激的

相关问题