redis作为数据库缓存的业务代码
以下是一个使用Redis作为数据库缓存的示例业务代码,假设业务逻辑是查询用户信息:
import redis
import json
import pymysql
# 初始化Redis连接
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0)
# 初始化MySQL连接
mysql_conn = pymysql.connect(host='localhost', user='root', password='password', db='test', charset='utf8')
# 查询用户信息
def get_user_info(user_id):
# 先从Redis缓存中查询
user_info = redis_client.get('user_info:' + str(user_id))
if user_info:
# 如果缓存中有,直接返回缓存中的数据
return json.loads(user_info.decode())
else:
# 如果缓存中没有,从MySQL中查询
cursor = mysql_conn.cursor()
cursor.execute('SELECT * FROM user WHERE id = %s', user_id)
result = cursor.fetchone()
if result:
# 将结果存储到Redis缓存中
redis_client.set('user_info:' + str(user_id), json.dumps(result))
return result
else:
return None
在上述代码中,我们先初始化了Redis和MySQL的连接,然后编写了一个get_user_info()函数用于查询用户信息。在函数中,我们先从Redis缓存中查询用户信息,如果缓存中有,则直接返回缓存中的数据。如果缓存中没有,则从MySQL中查询用户信息,并将查询结果存储到Redis缓存中。这样,下次再查询相同的用户信息时,就可以直接从Redis缓存中获取,从而提高查询效率
原文地址: https://www.cveoy.top/t/topic/cuLA 著作权归作者所有。请勿转载和采集!