redis监控键的改变

一: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)
原文地址:https://www.cnblogs.com/meloncodezhang/p/13669896.html