Skip to content

缓存、流控、迁移与治理:练习答案 ​

练习解答 ​

保存answer.py运行python answer.py:

python
import asyncio
async def main():
    gate=asyncio.Semaphore(1)
    active=peak=0
    async def one():
        nonlocal active,peak
        async with gate:
            active+=1;peak=max(peak,active)
            try:await asyncio.sleep(0.01)
            finally:active-=1
    await asyncio.gather(*(one() for _ in range(5)))
    assert peak==1 and active==0
    print('peak',peak)
asyncio.run(main())

并发仅限制同时在途数,请求处理很快时一分钟仍可发送很多次,需要另加按时间窗口计数的速率策略。

用心记录每一步成长