1.3 實現代碼:使用字符串鍵緩存單項數據
代碼清單1-1展示了基于1.2節所述解決方案實現的緩存程序。
代碼清單1-1 基本的緩存程序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)
提示:提高過期時間精度
如果需要更精確的過期時間,那么可以把緩存程序中過期時間的精度參數從代表秒的ex
修改為代表毫秒的px
。
作為例子,下面這段代碼展示了這個緩存程序的基本用法。
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.