相似同时协程减速器
async-reduce的Python项目详细描述
关于异步减少
async_reduce(coroutine)
允许聚合所有相似的同时就绪
运行coroutine
s并减少到只运行一个coroutine
。
其他聚合的coroutine
将从单个coroutine
获得结果。
它可以在 类似的异步操作,减少内部系统的负载。
快速示例
fromasync_reduceimportasync_reduceasyncdeffetch_user_data(user_id:int)->dict:"""" Get user data from inner service """url='http://inner-service/user/{}'.format(user_id)returnawaithttp.get(url,timeout=10).json()@web_server.router('/users/(\d+)')asyncdefhandler_user_detail(request,user_id:int):""" Handler for get detail information about user """# all simultaneous requests of fetching user data for `user_id` will # reduced to single requestuser_data=awaitasync_reduce(fetch_user_data(user_id))# sometimes ``async_reduce`` cannot detect similar coroutines and# you should provide special argument `ident` for manually determinationuser_statistics=awaitasync_reduce(DataBase.query('user_statistics').where(id=user_id).fetch_one(),ident='db_user_statistics:{}'.format(user_id))returnResponse(...)
在该示例中,如果客户端执行n,则不使用async_reduce
同时请求,如GET http://web_server/users/42
web\u server
对inner service和n查询database执行n请求。
总共:n同时请求向内部系统发出2*n请求。
使用async_reduce
如果客户端执行n同时请求web服务器
执行one对inner service和one的请求对database的查询。
总共:n同时请求只向内部系统发出2请求。
见其他真实的examples。
相似协程的确定
async_reduce(coroutine)
尝试通过散列本地
变量在调用时有界。如果:
- 其中一个参数不可哈希
- 协程函数是一种具有特定状态的类方法(如orm)
- coroutine函数具有对不可更改变量的闭包
通过将自定义键设置为参数ident
,可以禁用自动确定。
用作装饰器
库还提供特殊的装饰符@async_reduceable()
,例如:
fromasync_reduceimportasync_reduceable@async_reduceable()asyncdeffetch_user_data(user_id:int)->dict:"""" Get user data from inner service """url='http://inner-servicce/user/{}'.format(user_id)returnawaithttp.get(url,timeout=10).json()@web_server.router('/users/(\d+)')asyncdefhandler_user_detail(request,user_id:int):""" Handler for get detail information about user """returnawaitfetch_user_data(user_id)
挂钩
库支持挂钩。附加挂钩:
- debughooks-打印所有已触发的挂钩
- statisticsOverall挂钩-使用
async_reduce
的一般统计信息 - statisticsdetailhooks-类似于
StatisticsOverallHooks
但是细节统计 关于由async_reduce
处理的所有
coroutine
示例:
fromasync_reduceimportAsyncReducerfromasync_reduce.hooksimportDebugHooks# define custom async_reduce with hooksasync_reduce=AsyncReducer(hooks=DebugHooks())asyncdefhandler_user_detail(request,user_id:int):user_data=awaitasync_reduce(fetch_user_data(user_id))
请参阅examples/example_hooks.py中的更多详细示例。
您可以通过inherit fromBaseHooks编写自定义钩子。
注意事项
如果单个
coroutine
引发异常,则所有聚合的coroutine
将获得 同样的例外如果单个
coroutine
被卡住,所有聚合的coroutine
也将被卡住。 限制coroutine
的执行时间,并添加重试(可选)以避免它。从
coroutine
返回可变值时要小心,因为单个值 将共享。更喜欢使用不可变的值作为协程返回。