我們在「【⚡ Cache伺服器 - Redis】 讓系統服務更加順暢的快取機制」 分享如何使用Docker架設Redis, 在進入此篇章之前也請您親自架設一遍, 這樣才能加深學習的效果, 接下來我們會使用Python這套程式語言進行示範與說明, 讓我們以實戰的方式來練習, 將技術內化為知識, 達到真正的學以致用。
重點預告

安裝Python的pip套件
pip install redis
連線的單例模式
在存取快取伺服器Redis最重要的莫過於連線了, 如果連線都做不好了, 那後續的操作也不用說了, 因此學會如何連線就顯得非常重要, 這邊我們會搭配物件導向中的單例模式Singleton來設計連線, 讓我們在各模組之間盡情暢用, 避免多次的建立連線!
import redis
class RedisClient:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls._create_connection()
return cls._instance
@classmethod
def _create_connection(cls):
redis_host = 'localhost'
redis_port = 6379
redis_db = 0
try:
client = redis.Redis(
host=redis_host,
port=redis_port,
db=redis_db,
decode_responses=True
)
# 測試連接
client.ping()
return client
except redis.ConnectionError as e:
print(f"Redis連接失敗: {str(e)}")
return None
@classmethod
def reset_instance(cls):
"""重置Redis實例, 用於測試或重新連接"""
if cls._instance:
cls._instance.close()
cls._instance = None
在其他模組只需要這樣用 😌
from xxx.client import RedisClient
redis_client = RedisClient.get_instance()
# 開始操作redis...
幾個重要的參數說明 🐉
- redis_db:
- 這個部份是邏輯數據庫的概念,每個數據庫都獨立資料, 避免互相干擾。
- 用號碼表示: 0 ~ N。
- 範圍: 預設16個邏輯數據庫。
- 適用於多租戶、大型系統…。
- decode_responses:
- 解碼為utf-8。
- False: b'value’。
- True: 'value’。
鍵值
既然Redis主打Key、Value的資料庫系統, 那鍵值Key就格外的重要了,這邊我們先針對Key的規則設計做一個簡介, 雖然我們可以自由的訂定Key值, 但還是參考一些指南對於未來維護上會比較輕鬆一些。
- 以 : 隔開。
- <大類>:<子類>:<屬性>
- order:<order_id>:status
在Python這邊我們可以使用Enum的動態樣板來進行鍵值的設計。
from enum import Enum
class RedisKey(str, Enum):
ORDER_STATUS = 'order:001:{status}'
from types import RedisKey
# order:001:prepare
key = RedisKey.ORDER_STATUS.value.format(status='prepare')
關於這部份, 非常推薦您閱讀以下篇章, 裡面會有詳細的介紹:
簡易請求
這是我們一般使用Redis最簡易的請求方式, 搭配我們上述的連線, 請您親自操作看看。
from xxx.client import RedisClient
redis_client = RedisClient.get_instance()
# 取值
value = redis_client.get('key')
# 存值
redis_client.set('key', 'value')
批次請求
假設我們有一個操作是需要將一捆清單的key、value存放到Redis, 照著我們上述的簡易請求方法, 那會有多次的網路傳輸, 因此我們可以試著將這些動作使用所謂的pipeline, 並一次傳輸給Redis做操作。
# 建立 Pipeline
pipeline = redis_client.pipeline()
# 將多個指令加入 Pipeline
for i in range(5):
pipeline.set(f"key{i}", f"value{i}")
# 執行 Pipeline
pipeline.execute()
結語
操作Redis相對於一般資料庫系統已經簡單的許多了, 但其中還是有一些隱藏的細節值得我們去一一探索, 只有不斷的學習才能夠讓我們避開陷阱, 更好的掌握一套工具, 更有效率的完成任務, 尤其在複雜的大型系統中, 快取的技巧就顯得非常的重要, 我們只要掌握好Redis, 就能夠提昇使用者順暢的體驗, 進而影響客戶對我們系統的評價。