《Redis应用实例》书摘(1):缓存单项数据

因为Redis把数据储存在内存里面,并且提供了方便的键值对索引方式以及多样化的数据类型,所以使用Redis作为缓存是Redis最常见的用法之一。

代码清单 CODE_BASIC_CACHE 展示了基于这一原理实现的缓存程序。


代码清单 CODE_BASIC_CACHE 基本的缓存程序 cache.py

class Cache:

    def __init__(self, client):
        self.client = client

    def set(self, name, content, ttl=None):
        """
        为指定名字的缓存设置内容。
        可选的ttl参数用于设置缓存的生存时间。
        """
        if ttl is None:
            self.client.set(name, content)
        else:
            self.client.set(name, content, ex=ttl)

    def get(self, name):
        """
        尝试获取指定名字的缓存内容,若缓存不存在则返回None。
        """
        return self.client.get(name)

作为例子,代码清单 CODE_USAGE_BASIC_CACHE 展示了这个缓存程序的基本用法。


代码清单 CODE_USAGE_BASIC_CACHE 缓存程序的基本用例 cache_usage.py

from redis import Redis
from cache import Cache

ID = 10086
TTL = 60
REQUEST_TIMES = 5

client = Redis(decode_responses=True)
cache = Cache(client)

def get_content_from_db(id):
    # 模拟从数据库中取出数据
    return "Hello World!"

def get_post_from_template(id):
    # 模拟使用数据和模板生成HTML页面
    content = get_content_from_db(id)
    return "<html><p>{}</p></html>".format(content)

for _ in range(REQUEST_TIMES):
    # 尝试直接从缓存中取出HTML页面
    post = cache.get(ID)
    if post is None:
        # 缓存不存在,访问数据库并生成HTML页面
        # 然后把它放入缓存以便之后访问
        post = get_post_from_template(ID)
        cache.set(ID, post, TTL)
        print("Fetch post from database&template.")
    else:
        # 缓存存在,无需访问数据库也无需生成HTML页面
        print("Fetch post from cache.")

根据这段程序的执行结果可知,程序只会在第一次请求时访问数据库并根据模板生成HTML页面,而后续一分钟内发生的其他请求都是通过访问Redis保存的缓存来完成的:

$ python3 cache_usage.py
Fetch post from database&template.
Fetch post from cache.
Fetch post from cache.
Fetch post from cache.
Fetch post from cache.

Tip

本文摘录自《Redis应用实例》一书。
欢迎访问书本主页以了解更多Redis使用案例:huangz.works/rediscookbook/
../_images/rediscookbook-banner.png