重新思考数据库的异步连接池
async-repool的Python项目详细描述
async-repool
是一个python库,它提供了一个基于异步的连接池管理,用于访问rethinkdb数据库。async-repool
创建并维护一个可配置的活动连接池,该池连接到RethinkDB数据库。这些连接可以通过一个基本的api单独使用。
在内部,repool使用的pythonAsyncIO Queue类不是线程安全的。这意味着同一个连接池不能在多个线程之间共享,请改为对进程工作线程使用asyncio。
这只是repool的基于异步的克隆。
安装
async-repool
作为pypi上的python库提供。使用pip安装非常简单:
$ pip install async_repool
这将安装async-repool
,并重新考虑数据库依赖性。
基本用法
使用默认连接配置的新连接池可以通过以下方式创建:
fromasync_repoolimportAsyncConnectionPoolpool=AsyncConnectionPool(dict())# Required argument is kwargs for R.connect functionawaitpool.init_pool()conn=awaitpool.acquire()#returns a Connection instanceawaitr.table('heroes').run(conn)#do RethinkDB stuff# ...pool.release(conn)#put back connection to the poolawaitpool.release_pool()#release pool (close rethinkdb connections)# ...asyncwithpool.connect()asconn1:# do something with conn1# pool.release(conn1) is automatically called after leaving the with code block
可选参数
AsyncConnectionPool
创建接受许多可选参数:
pool_size
:设置池大小,即同时打开的连接数(默认值为3)。connection_ttl
:将连接时间设置为有效。超过ttl的连接将在获取时自动关闭并重新打开(默认值=3600秒,设置为0表示禁用)