【Redis與python交互】重點: Redis更多作爲一個緩存中介

1、讀寫

import redis

# 連接
r = redis.StrictRedis(host='localhost',port=6379,password='root')

# 方法1:根據數據類型不同,調用相應的方法
# 寫數據
r.set('p1','good')
# 讀數據 r.get()
print(r.get('p1'))

2、緩衝多條命令


import redis

# 連接
r = redis.StrictRedis(host='localhost',port=6379,password='root')

# pipeline
# 緩衝多條命令,然後依次執行,減少服務器-客戶端之間的TCP數據包
# 一次請求 執行多條語句
pipe = r.pipeline()
pipe.set('p2','fqx')
pipe.set('p2','is a')
pipe.set('p2','good')
pipe.set('p2','man')
pipe.execute()


3、封裝起來

import redis
class FqxRedis():
    def __init__(self,password,host='localhost',port=6379):
        self.__redis = redis.StrictRedis(host=host,port=port,password=password)

    def set(self,key,value):
        self.__redis.set(key,value)

    def get(self,key):
        if self.__redis.exists(key):
            return self.__redis.get(key)
        else:
            print('不存在此條數據')

 



Redis更多作爲一個緩存中介

客戶端發送請求信息先到 Redis 中判斷,若能找到用戶名,直接返回,如果找不到,到 mysql 中查詢

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章