如何用字典实现一个简单的缓存系统?请设计一个带有过期机制的缓存字典类。

from time import time

class ExpiringCache:
    def __init__(self):
        """
        初始化缓存字典和过期时间字典。
        """
        self._cache = {}
        self._expiry = {}

    def set(self, key, value, ttl=None):
        """
        设置缓存值,并可选地指定过期时间(秒)。

        参数:
            key: 缓存的键。
            value: 缓存的值。
            ttl: 过期时间(秒),默认为None(不过期)。
        """
        self._cache[key] = value
        if ttl is not None:
            self._expiry[key] = time() + ttl
        else:
            self._expiry.pop(key, None)

    def get(self, key):
        """
        获取缓存值,如果已过期或不存在则返回None。

        参数:
            key: 缓存的键。

        返回:
            缓存的值或None。
        """
        if key in self._expiry and time() > self._expiry[key]:
            self._cache.pop(key, None)
            self._expiry.pop(key, None)
            return None
        return self._cache.get(key)

    def delete(self, key):
        """
        删除缓存中的键值对。

        参数:
            key: 缓存的键。
        """
        self._cache.pop(key, None)
        self._expiry.pop(key, None)

    def clear(self):
        """
        清空所有缓存。
        """
        self._cache.clear()
        self._expiry.clear()

    def contains(self, key):
        """
        检查缓存是否包含某个键(未过期)。

        参数:
            key: 缓存的键。

        返回:
            bool, 键是否存在且未过期。
        """
        if key in self._expiry and time() > self._expiry[key]:
            self._cache.pop(key, None)
            self._expiry.pop(key, None)
            return False
        return key in self._cache

示例

# 创建缓存实例
cache = ExpiringCache()

# 设置缓存值,5秒后过期
cache.set('username', 'Alice', ttl=5)

# 获取缓存值
print(cache.get('username'))  # 输出: Alice

# 等待6秒后再次获取
import time
time.sleep(6)
print(cache.get('username'))  # 输出: None (已过期)

# 设置不过期的缓存
cache.set('language', 'Python')
print(cache.get('language'))  # 输出: Python

# 检查键是否存在
print(cache.contains('language'))  # 输出: True

# 删除键
cache.delete('language')
print(cache.contains('language'))  # 输出: False

# 清空缓存
cache.clear()
print(cache.get('username'))  # 输出: None

详细说明

  1. 初始化:ExpiringCache类初始化了两个字典_cache和_expiry,分别用于存储缓存值和过期时间。

  2. set方法:

    • 将键值对存入_cache字典。
    • 如果指定了ttl(过期时间),则在_expiry字典中记录键的过期时间戳(当前时间 + ttl)。
    • 如果未指定ttl,则确保键不在_expiry字典中(表示永不过期)。
  3. get方法:

    • 检查键是否在_expiry字典中且当前时间是否超过了过期时间。
    • 如果已过期,则删除键值对并返回None。
    • 否则,返回键对应的缓存值。
  4. delete方法:删除指定键的缓存值和过期时间记录。

  5. clear方法:清空所有缓存数据。

  6. contains方法:在检查键是否存在时,会先检查是否过期。如果过期,则删除键值对并返回False。

优点

  • 轻量级实现,依赖Python内置字典和时间模块。
  • 支持过期机制,适用于需要临时存储的场景。
  • 线程不安全,适用于单线程环境。

改进方向

  • 如果需要线程安全,可以添加锁机制。
  • 可以扩展为LRU(最近最少使用)缓存。