马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
前言
近来在学习《Redis应用实例》,这本书并没有讲任何底层,而是聚焦实战用法,梳理了 32 种 Redis 的常见用法。我的条记在
Github 上,用 Jupyter 纪录,会有更好的阅读体验,作者的源码在这里:https://github.com/huangzworks/rediscookbook?tab=readme-ov-file 。
缓存文本数据
利用 Redis 缓存体系中的文本数据,这些数据可能只有单独的一项,也可能会由多个项组成。
- """
- 配置连接
- """
- 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,然后输出。
- """
- 所需要的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)
复制代码- """
- 实现逻辑:
- 先从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 的哈希或其他数据结构进行存储。
- """
- 所需要的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
复制代码- """
- 实现逻辑:
- 和上面的一样
- """
- 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 脚本的对比》。
- """
- 所需要的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
复制代码- """
- 实现逻辑:
- 和上面的一样
- """
- hashCache = HashCache(client)
- # 字典
- data = {"id": 10086, "name": "Peter", "gender": "male", "age": 18}
- hashCache.set("Hash_Cache", data, 60)
- # get逻辑和上面的一样,省略
- print(hashCache.get("Hash_Cache"))
复制代码 免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|