我正在阅读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))在必要时,使用池而不是连接有什么好处?
发布于 2017-03-05 00:46:41
建立与数据库服务器的连接是一项开销很大的操作。连接池是一种常见的技术,可以避免支付该成本。连接池使连接保持开放状态,并在必要时将其出租。
通过执行一个简单的基准测试,很容易看到池的好处:
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倍。
发布于 2020-03-30 06:01:13
Elvis 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负责这件事,而我
bench_asyncpg_pool上的1.62和
bench_asyncpg_con上的63.18
我在使用这个库方面有点新手,并且认为整个项目的一个连接con会是一个很好的选择。如果我错了,请纠正我。我会很感激的
https://stackoverflow.com/questions/42242093
复制相似问题