6.4 异步 Redis 客户端如果需要完全异步操作,可以使用 aioredis:pip install aioredis然后修改代码为:import aioredisredis_client = await aioredis.create_redis_pool("redis://localhost:6379/0")await redis_client.setex(cache_key, 60, json.dumps(result))7. 总结通过将 Redis 集成到 FastAPI 中,我们可...
pip install fastapi-cache2 1. 4.1 fastapi-cache的官网示例 这里我直接贴它官网的示例的代码吧: import aioredis from fastapi import FastAPI from starlette.requests import Request from starlette.responses import Response from fastapi_cache import FastAPICache from fastapi_cache.backends.redis import RedisBack...
首先在缓存中检查数据是否存在,如果存在则返回缓存数据;如果不存在,则从某个数据源(例如数据库)获取数据,并将其存入 Redis。 @app.get("/items/{item_id}") async def read_item(item_id: int): cache_key = f"item:{item_id}" # 缓存键 cached_data = redis_client.get(cache_key) #从 Redis ...
这个装饰器将检查Redis中是否存在缓存的数据,如果存在则直接返回缓存的数据,否则执行实际的函数并将结果存储到Redis中: python from functools import wraps from typing import Any, Callable, Coroutine, Dict, TypeVar F = TypeVar("F", bound=Callable[..., Coroutine[Any, Any, Dict]]) async def cache(re...
value =awaitredis.get(key)ifvalue:return{"key": key,"value": value.decode()}else:return{"message":f"Key{key}not found"} app.include_router(router)if__name__ =="__main__": uvicorn.run("rediss:app", host="0.0.0.0", port=8089, reload=True, ) ...
pip install starlette-cache[redis] 接着更新main.py文件,引入缓存支持: # main.pyfromfastapiimportFastAPIimporttimefromstarlette.requestsimportRequestfromstarlette.responsesimportResponsefromstarlette.middleware.cachingimportCacheControlfromstarlette_cacheimportcaches ...
app.state.redis_client.pipeline(transaction=True) as pipe: # 批量进行管道操作 ok1, ok2 = await (pipe.set('xiaoxiao', '测试数据').set('xiaoxiao2','测试数据2').execute()) async with request.app.state.redis_client.pipeline(transaction=True) as pipe: cache1, cache2 = await (pipe.get...
添加缓存:只用redis的Hash数据类型添加缓存。 例如:需要在查询的业务功能中,添加缓存 1.首先需要在执行...
安装Redis 并配置缓存: pip install starlette-cache[redis] 在main.py中初始化缓存: # main.pyfromstarlette_cacheimportcaches cache = caches.get("default")@app.on_event("startup")asyncdefstartup_event():# 初始化缓存awaitcache.initialize("redis://localhost:6379/0") ...
usesFastAPI+get()Redis+setex()+get() 状态图 以下是使用 Mermaid 语法生成的状态图,用于展示 API 请求的状态变化: hitmissStartCheck_CacheCache_HitCompute_ResultReturn_ResultStore_Cache 结尾 通过以上步骤,你已经成功实现了使用 FastAPI 和 Redis 进行缓存的基本功能。这个过程不仅提升了应用的性能,也为后续的...