feat: 使用redis来缓存用户信息
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Annotated
|
||||
from typing import Annotated, AsyncContextManager
|
||||
|
||||
import redis.asyncio as redis
|
||||
from fastapi import Depends
|
||||
@@ -38,7 +38,7 @@ class RedisUtils():
|
||||
|
||||
# 获取一个Redis连接客户端
|
||||
@asynccontextmanager
|
||||
async def get_redis_connection(self):
|
||||
async def get_redis_connection(self) -> AsyncContextManager[redis.Redis]:
|
||||
if not self.redis_pool:
|
||||
raise Exception("Redis 连接池未初始化")
|
||||
redis_client = redis.Redis(connection_pool=self.redis_pool)
|
||||
@@ -63,3 +63,26 @@ async def get_redis_client() -> redis.Redis:
|
||||
|
||||
|
||||
RedisClientDep = Annotated[redis.Redis, Depends(get_redis_client)]
|
||||
|
||||
|
||||
# 从redis中获取key的缓存,如果没有值则执行默认值获取函数,并保存到redis中
|
||||
async def get_redis_cache(key: str, default_value_getter):
|
||||
async with redis_utils.get_redis_connection() as redis_client:
|
||||
mapping = await redis_client.hgetall(key)
|
||||
exists = bool(mapping)
|
||||
if exists:
|
||||
return mapping
|
||||
else:
|
||||
value = await default_value_getter()
|
||||
print("value", value)
|
||||
if value is not None:
|
||||
new_value = {k: v for k, v in value.items() if v is not None}
|
||||
await redis_client.hset(key, mapping=new_value)
|
||||
return value
|
||||
|
||||
|
||||
# 删除redis缓存
|
||||
async def remove_redis_cache(key: str):
|
||||
async with redis_utils.get_redis_connection() as redis_client:
|
||||
result = await redis_client.delete(key)
|
||||
return result > 0 # 返回是否删除成功
|
||||
|
||||
Reference in New Issue
Block a user