1. 程式人生 > >Redis實現mysql功能

Redis實現mysql功能

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('查無此資訊')