asyncpg - 连接vs连接池
问题描述:
我将通过asyncpg
的文档,并且我无法理解为什么使用连接池而不是单个连接。asyncpg - 连接vs连接池
在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))
什么用池在必要的连接优势?
答
建立与数据库服务器的连接是一项昂贵的操作。连接池是允许避免支付该成本的常用技术。游泳池将连接打开并在必要时将其租出。
很容易做一个简单的基准看到了池的好处:
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倍。