import pymysql,redis
def selectFromMySQL(_id): #传入产品的id,通过SQL查询
conn = pymysql.Connect(
host = '10.35.165.97',
port = 3306,
user = 'root',
passwd = '123456',
db = 'mydb',
charset = 'utf8'
)
cursor = conn.cursor()
sql = "select _id,proname,price from product where _id=%d"
cursor.execute(sql%_id)
product = cursor.fetchone()
cursor.close()
conn.close()
return product
def selectFromRedis(_id): #从redis中查数据
r = redis.Redis('10.35.165.97',6379)
return r.hgetall('product:info:' + str(_id)) #通过hash的key获得对应的所有field_value
def saveToRedis(product):#将MySQL中查询出的产品信息以hash结构的形式存储于Redis中
r = redis.Redis('10.35.165.97', 6379)
r.hmset('product:info:' + str(product[0]),{'_id':product[0],'proname':product[1],'price':product[2]})
_id = 10
product = selectFromMySQL
product_redis = selectFromRedis(_id)
if product_redis:
print("查询redis缓存")
result = {}
for k,v in product_redis.items():
result[k.decode()] = v.decode()
print(result)
else:
print('缓存中不存在,查询MySQL')
product_mysql = selectFromMySQL(_id) #如果缓存中不存在,则查MySQL
if product_mysql:
saveToRedis(product_mysql) #如果在MySQL中查询到了,则存储在Redis中
print("已经保存至Redis")
print(product_mysql)
else:
print('查无此信息')
def selectFromMySQL(_id): #传入产品的id,通过SQL查询
conn = pymysql.Connect(
host = '10.35.165.97',
port = 3306,
user = 'root',
passwd = '123456',
db = 'mydb',
charset = 'utf8'
)
cursor = conn.cursor()
sql = "select _id,proname,price from product where _id=%d"
cursor.execute(sql%_id)
product = cursor.fetchone()
cursor.close()
conn.close()
return product
def selectFromRedis(_id): #从redis中查数据
r = redis.Redis('10.35.165.97',6379)
return r.hgetall('product:info:' + str(_id)) #通过hash的key获得对应的所有field_value
def saveToRedis(product):#将MySQL中查询出的产品信息以hash结构的形式存储于Redis中
r = redis.Redis('10.35.165.97', 6379)
r.hmset('product:info:' + str(product[0]),{'_id':product[0],'proname':product[1],'price':product[2]})
_id = 10
product = selectFromMySQL
product_redis = selectFromRedis(_id)
if product_redis:
print("查询redis缓存")
result = {}
for k,v in product_redis.items():
result[k.decode()] = v.decode()
print(result)
else:
print('缓存中不存在,查询MySQL')
product_mysql = selectFromMySQL(_id) #如果缓存中不存在,则查MySQL
if product_mysql:
saveToRedis(product_mysql) #如果在MySQL中查询到了,则存储在Redis中
print("已经保存至Redis")
print(product_mysql)
else:
print('查无此信息')