一:redis監控鍵的變化,在我修改這個鍵的過程中,這個鍵被別人修改了,那就拋出異常
import time import redis class Redis_Test(object): def __init__(self): self.client = redis.StrictRedis(host="xxx", port=6379, db=0,decode_responses=True) def transaction_set_str(self): with self.client.pipeline() as pipe: while True: try: """監視一個key,在我執行期間被修改立馬會拋出異常""" # 1. 對指定的key進行監視,我修改前別人不能修改 pipe.watch("s1") count = int(pipe.get("s1")) print(count) if count > 0: # 2. 開啟管道事務 pipe.multi() pipe.set("s1",count -1) pipe.execute() else: break except Exception as e: print(e) return "fuck" if __name__ == '__main__': redis_client = Redis_Test() result = redis_client.transaction_set_str() print(result)