头歌 Redis安全与性能

第1关:持久化

在这里插入图片描述

第2关:复制

在这里插入图片描述

第3关:Redis事务与流水线

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import time
import redis

conn = redis.Redis()

# 将商品放到平台上
def add_item_to_market(itemid, sellerid, price):
    # 请在下面完成要求的功能
    #********* Begin *********#
    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
    #********* End *********#

# 购买商品
def purchase(buyerid, itemid):
    # 请在下面完成要求的功能
    #********* Begin *********#
    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
    #********* End *********#
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值