pip3 install redis
1.创建 Redis 连接池
文件地址:db/redis_db.py
代码尝试连接到本地运行的 Redis 服务器,并设置数据库为 1,最大连接数为 20。
如果连接过程中出现任何异常,它会捕获异常并打印错误信息。
import redis
try:
pool = redis.ConnectionPool(
host='localhost',
port=6379,
db=1,
max_connections=20
)
except Exception as e:
print(e)
2.查找用于缓存的记录
文件地址:db/news_dao.py
用 sql 语言在 Navicat 中寻找要作为缓存的记录,
目的是将审批通过的信息,存进 Redis 数据库中。
#查找用于缓存的记录
def search_cache(self, id):
# 创建异常
try:
# 获得连接项
conn = pool.get_connection()
# 获得游标
cursor = conn.cursor()
# 创建sql
sql = """
SELECT n.title,u.username,t.type,n.content_id,n.is_top,n.create_time
FROM t_news n join t_type t on n.type_id=t.id
join t_user u on n.editor_id=u.id
where n.id=%s
"""
# 执行sql
cursor.execute(sql, [id])
# 获得查询结果
result = cursor.fetchone()
return result
# 返回获得结果
except Exception as e:
print(e)
finally:
if "conn" in dir():
conn.close()
3.操作Redis数据库
3.1 创建操作类
文件地址:db/redis_news_dao.py
创建一个 Python 类 RedisNewsDao
,它包含两个方法:insert
和 delete
,
分别用于添加与删除 Redis 数据库中的新闻数据。
3.1.1 添加数据
from db.redis_db import pool
import redis
class RedisNewsDao:
#添加数据
def insert(self,id,title,username,type,content,is_top,create_time):
conn = redis.Redis(
connection_pool=pool,
)
try:
#向redis中存放数据
conn.hmset(id,{
'title':title,
'author':username,
'type':type,
'content':content,
'is_top':is_top,
'create_time':create_time
})
#如果是今日热文则保留一天后销毁
if is_top &