python 版本 3.x
执行环境需要安装redis模块: pip install redis

 

 

执行脚本前,有redis-cli中查询key值:

 

 执行脚本:

 


****************************** redis的乐观锁 脚本如下 *****************************
import redis
def key_for(user_id):
return "account_{}".format(user_id)

def double_account(client, user_id):
key = key_for(user_id)
while True:
client.watch(key)
value = int(client.get(key))
value *=2
pipe = client.pipeline(transaction=True)
pipe.multi()
pipe.set(key,value)
try:
pipe.execute()
break
except redis.WatchError:
continue
return int(client.get(key))

if __name__ == "__main__":
client = redis.StrictRedis(host="192.168.1.100", port = 7000)
user_id = "abc"
client.setnx(key_for(user_id),5)
print (double_account(client,user_id))
posted on 2018-10-15 20:22  咖啡猫来啦  阅读(483)  评论(0编辑  收藏  举报