python鏈接redis哨兵集羣

一.redis集羣模式有多種, 哨兵模式只是其中的一種實現方式, 其原理請自行谷歌或者百度python

 

二.python 鏈接 redis 哨兵集羣redis

  1. 安裝redis包數據庫

pip install redis

  2.實現鏈接邏輯socket

from redis.sentinel import Sentinel
from redis import WatchError
MYSETINEL = None
MASTER = None
SLAVE = None

# 1.redis 哨兵模式集羣最少須要一主三從, 三哨兵
# 2.redis 哨兵集羣全部主從節點都完整的保存了一份數據
SENTINEADDRESS = [('127.0.0.1', 6390), ('127.0.0.1', 6391), ('127.0.0.1', 6392)]


def get_redis_conn():

    global MYSETINEL
    global MASTER
    global SLAVE
# 若是哨兵鏈接實例已存在, 不重複鏈接, 當鏈接失效時, 從新鏈接 if not MYSETINEL:# 鏈接哨兵 MYSETINEL = Sentinel(SENTINEADDRESS, socket_timeout=2000) # 嘗試鏈接最長時間單位毫秒, 1000毫秒爲1秒 # 經過哨兵獲取主數據庫鏈接實例 參數1: 主數據庫的名字(集羣部署時在配置文件裏指明) MASTER = MYSETINEL.master_for('seckill', socket_timeout=2000) # 經過哨兵獲取從數據庫鏈接實例 參數1: 從數據的名字(集羣部署時在配置文件裏指明) SLAVE = MYSETINEL.slave_for('seckill', socket_timeout=2000)
# 每次都先嚐試生成鏈接實例 get_redis_conn()
# 往 主數據庫 寫入數據 def setcache(key, time, value): global MASTER if MASTER: return MASTER.setex(key, time, value) else: return False # 從 從數據庫 讀取數據 def getcache(key): global SLAVE if SLAVE: return SLAVE.get(key) else: return False

  3. 使用示例1: 使用管道嘗試修改商品庫存spa

from redis import WatchError


# 使用事物修改商品庫存
def update_stock(key):
    global MASTER
    with MASTER.pipeline() as pipe:
        i = 0
        while i < 10:  # 嘗試修改庫存10次
            try:
                # watch庫存鍵, multi後若是該key被其餘客戶端改變, 事務操做會拋出WatchError異常
                pipe.watch(key)
                count = int(pipe.get(key))  # 取庫存
                # 能夠修改庫存
                if count > 0:
                    pipe.set(key, count-1)  # 保存剩餘庫存
                    # 事務結束, 把命令推送過去
                    result = pipe.execute()  # execute返回命令執行結果列表,
                    return True, result
                # 庫存不足
                else:
                    pipe.unwatch()
                    return False
            except WatchError as e:
                print(e)
                i += 1
                continue
            finally:
                pipe.reset()
相關文章
相關標籤/搜索