面试题答案
一键面试设计思路
- 协程池:创建一个协程池来管理并发请求,避免无限制创建协程导致资源耗尽。
- 任务队列:将玩家获取角色信息的请求放入任务队列,协程从任务队列中取出任务执行。
- 负载均衡:可以采用轮询、随机等方式从任务队列分配任务给协程,确保每个协程的负载相对均衡。
- 缓存机制:为了加快响应速度,引入缓存来存储经常访问的角色信息,协程先从缓存中获取数据,若不存在再从数据库加载。
关键代码片段(Python 示例)
import asyncio
import queue
# 模拟获取角色信息的函数
async def get_character_info(character_id):
await asyncio.sleep(1) # 模拟数据库查询延迟
return f"Character {character_id} info"
# 协程工作函数
async def worker(task_queue, cache):
while True:
try:
character_id = task_queue.get_nowait()
if character_id in cache:
result = cache[character_id]
else:
result = await get_character_info(character_id)
cache[character_id] = result
print(f"Processed character {character_id}: {result}")
except queue.Empty:
break
# 主函数
async def main():
task_queue = queue.Queue()
cache = {}
num_workers = 10 # 协程数量
character_ids = [1, 2, 3, 4, 5] # 模拟请求的角色 ID 列表
for id in character_ids:
task_queue.put(id)
workers = [worker(task_queue, cache) for _ in range(num_workers)]
await asyncio.gather(*workers)
if __name__ == "__main__":
asyncio.run(main())
在这段代码中:
get_character_info
模拟从数据库获取角色信息的异步操作。worker
是协程工作函数,从任务队列中获取任务,先检查缓存,若没有则获取并更新缓存。main
函数初始化任务队列、缓存和协程池,并将任务放入队列,最后等待所有协程完成。