Skip to main content

redis_cache

RedisCache

class RedisCache(AbstractCache)

RedisCache 是使用 Redis 数据库实现的 AbstractCache 接口。

该类提供了使用 Redis 数据库进行数据缓存的具体实现。

属性

  • seed Union[str, int] - 用作缓存键前缀的种子或命名空间。
  • cache redis.Redis - 用于缓存的 Redis 客户端。

方法

init(self, seed, redis_url): 使用给定的种子和 Redis URL 初始化 RedisCache。 _prefixed_key(self, key): 内部方法,用于获取带命名空间的缓存键。 get(self, key, default=None): 从缓存中检索项目。 set(self, key, value): 在缓存中设置项目。

  • close(self) - 关闭 Redis 客户端。
  • __enter__(self) - 上下文管理入口。 exit(self, exc_type, exc_value, traceback): 上下文管理退出。

__init__

def __init__(seed: Union[str, int], redis_url: str)

初始化 RedisCache 实例。

参数

  • seed Union[str, int] - 用于缓存的种子或命名空间。这将作为所有缓存键的前缀。
  • redis_url str - Redis 服务器的 URL。

get

def get(key: str, default: Optional[Any] = None) -> Optional[Any]

从 Redis 缓存中检索项目。

参数

  • key str - 缓存中项目的键。
  • default optional - 如果未找到键,则返回的默认值。默认为 None。

返回值

如果找到键,则返回与键关联的反序列化值;否则返回默认值。

set

def set(key: str, value: Any) -> None

在 Redis 缓存中设置项目。

参数

  • key str - 要存储项目的键。
  • value - 要存储在缓存中的值。

注意

在存储到 Redis 之前,该值将使用 pickle 进行序列化。

close

def close() -> None

关闭 Redis 客户端。

执行任何必要的清理操作,例如关闭网络连接。

__enter__

def __enter__() -> Self

进入与对象相关的运行时上下文。

返回值

  • self - 实例本身。

__exit__

def __exit__(exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType]) -> None

退出与对象相关的运行时上下文。

执行清理操作,例如关闭 Redis 客户端。

参数

  • exc_type - 如果在上下文中引发了异常,则为异常类型。
  • exc_value - 如果在上下文中引发了异常,则为异常值。
  • traceback - 如果在上下文中引发了异常,则为异常的回溯信息。