import redis.asyncio as redis from config import redis_settings # 创建Redis连接池 redis_pool = redis.ConnectionPool.from_url( redis_settings.url, decode_responses=True ) async def get_redis(): """获取Redis连接""" async with redis.Redis(connection_pool=redis_pool) as conn: try: yield conn finally: await conn.close() async def set_token_in_redis(redis_conn, user_id: int, token: str, expire_seconds: int): """将令牌存储到Redis""" key = f"user:token:{user_id}" await redis_conn.set(key, token, ex=expire_seconds) async def get_token_from_redis(redis_conn, user_id: int): """从Redis获取令牌""" key = f"user:token:{user_id}" return await redis_conn.get(key) async def delete_token_from_redis(redis_conn, user_id: int): """从Redis删除令牌""" key = f"user:token:{user_id}" await redis_conn.delete(key) async def check_token_in_redis(redis_conn, user_id: int, token: str): """检查令牌是否在Redis中且有效""" stored_token = await get_token_from_redis(redis_conn, user_id) return stored_token == token