asyncpg - connection vs connection pool

前端 未结 2 1658
广开言路
广开言路 2021-02-04 15:18

I am going over asyncpg\'s documentation, and I am having trouble understanding why use a connection pool instead of a single connection.

In the example given, a pool is

2条回答
  •  死守一世寂寞
    2021-02-04 15:45

    Establishing a connection to a database server is an expensive operation. Connection pools are a common technique allowing to avoid paying that cost. A pool keeps the connections open and leases them out when necessary.

    It's easy to see the benefits of a pool by doing a simple benchmark:

    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)
    

    The above completes on my machine in 1.568 seconds.

    Whereas the pool version:

    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)
    

    Runs in 0.234 seconds, or 6.7 times faster.

提交回复
热议问题