前言
最近在学习《Redis应用实例》,这本书并没有讲任何底层,而是聚焦实战用法,梳理了 32 种 Redis 的常见用法。我的笔记在
Github 上,用 Jupyter 记录,会有更好的阅读体验,作者的源码在这里:https://github.com/huangzworks/rediscookbook?tab=readme-ov-file 。
缓存文本数据
使用 Redis 缓存系统中的文本数据,这些数据可能只有单独的一项,也可能会由多个项组成。
python
"""
配置连接
"""
from redis import Redis
# Redis连接配置
client = Redis(
host='39.104.208.122',
port=6379,
decode_responses=True, # 自动解码
ssl=False
)
if client.ping():
print("Redis连接成功")
else:
print("Redis连接失败")
1. 使用字符串键缓存单项数据
有些时候,业务非常简单,需要缓存的数据可能只有单独一项,比如一个页面 ...。这种情况只需一个 String 即可满足。
代码实现的逻辑就是先从 Redis 中直接拿 cache,如果有,则直接输出;如果没有,从数据库中提取,然后存入 Redis,然后输出。
python
"""
所需要的Redis基础操作
"""
class Cache:
def __init__(self, client):
self.client = client
def set(self, name, content, ttl=None):
"""设置缓存内容,可选TTL过期时间"""
self.client.set(name, content, ttl)
def get(self, name):
"""获取缓存内容,不存在返回None"""
# GET name
return self.client.get(name)
python
"""
实现逻辑:
先从Redis中直接拿cache,如果有,则直接输出;如果没有,从数据库中提取,然后存入Redis,然后输出
"""
# 初始化
cache = Cache(client)
def get_content_from_db():
"""模拟从数据库中取出数据"""
return "<html><p>Hello World!</p></html>"
# 先直接尝试从Redis中拿
content = cache.get("HTML_Catch")
if content is None:
# 缓存不存在,访问数据库拿到数据
content = get_content_from_db()
# 然后把它放入缓存以便之后访问
cache.set("HTML_Catch", content, 60)
print(content)
else:
# 缓存存在,无需访问数据库,直接从Redis中拿到数据
print(content)
2. 使用 JSON/哈希键缓存多项数据
大部分时候,单项数据是少数的,更多的是由多个元素组成的数据,比如对从数据库读到的一行字段 {"id": 10086, "name": Peter, "gender": "male", "age": 18} 进行存储,有两种处理方式:
- 第一种方式是用 JSON 等序列化手段,将多个数据打包为单项进行存储;
- 第二种方式可以直接使用 Redis 的哈希或其他数据结构进行存储。
python
"""
所需要的Redis基础操作(JSON)
"""
import json
class JsonCache:
def __init__(self, client):
self.cache = Cache(client)
def set(self, name, content, ttl=None):
"""设置缓存内容,并对其进行JSON序列化,可选TTL过期时间"""
json_data = json.dumps(content)
self.cache.set(name, json_data, ttl)
def get(self, name):
"""获取缓存内容,不存在返回None"""
json_data = self.cache.get(name)
if json_data is not None:
return json.loads(json_data)
else:
return None
python
"""
实现逻辑:
和上面的一样
"""
jsonCache = JsonCache(client)
# 字典
data = {"id": 10086, "name": "Peter", "gender": "male", "age": 18}
jsonCache.set("JSON_Cache", data, 60)
# get逻辑和上面的一样,省略
print(jsonCache.get("JSON_Cache"))
对于第二种通过哈希的操作,Redis 的哈希命令无法一个命令实现存值和设置过期时间,会涉及到两个命令。为了保证两个命令的原子执行,也就是不受其它命令干扰,可以使用事务的方式。
关于 Pipeline、事务、Lua 的使用,我写了一篇博客,可以帮助更好的理解,《Redis 的指令执行方式:Pipeline、事务与 Lua 脚本的对比》。
python
"""
所需要的Redis基础操作(哈希)
"""
class HashCache:
def __init__(self, client):
self.client = client
def set(self, name, content, ttl=None):
"""设置缓存内容,可选TTL过期时间"""
if ttl is None:
self.client.hset(name, mapping=content)
else:
# 使用pipeline发送多条命令
tx = self.client.pipeline() # tx是transaction的缩写
# HSET name field value [field value] [...]
tx.hset(name, mapping=content)
# EXPIRE name ttl
tx.expire(name, ttl)
# EXEC
tx.execute()
def get(self, name):
"""获取缓存内容,不存在返回{}"""
# HGETALL name
result = self.client.hgetall(name)
return result
python
"""
实现逻辑:
和上面的一样
"""
hashCache = HashCache(client)
# 字典
data = {"id": 10086, "name": "Peter", "gender": "male", "age": 18}
hashCache.set("Hash_Cache", data, 60)
# get逻辑和上面的一样,省略
print(hashCache.get("Hash_Cache"))