第1关:持久化
第2关:复制
第3关:Redis事务与流水线
import time
import redis
conn = redis.Redis()
def add_item_to_market(itemid, sellerid, price):
repertory = "inventory:" + sellerid
item = itemid + "." + sellerid
end = time.time() + 5
pipe = conn.pipeline()
while time.time() < end:
try:
pipe.watch(repertory)
if not pipe.sismember(repertory, itemid):
pipe.unwatch()
return None
pipe.multi()
pipe.zadd("market", item, price)
pipe.srem(repertory, itemid)
pipe.execute()
return True
except redis.exceptions.WatchError:
pass
return False
def purchase(buyerid, itemid):
item, sellerid = itemid.split(".")
buyer = "users:" + buyerid
seller = "users:" + sellerid
repertory = "inventory:" + buyerid
end = time.time() + 10
pipe = conn.pipeline()
while time.time() < end:
try:
pipe.watch("market", buyer)
price = pipe.zscore("market", itemid)
funds = int(pipe.hget(buyer, "funds"))
if funds < price:
pipe.unwatch()
return None
pipe.multi()
pipe.hincrby(seller, "funds", int(price))
pipe.hincrby(buyer, "funds", int(-price))
pipe.sadd(repertory, item)
pipe.zrem("market", itemid)
pipe.execute()
return True
except redis.exceptions.WatchError:
pass
return False