抢购业务模块(redis+mysql)

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

class CatchCouponService(object):
    """
    抢券活动操作
    """
    def __init__(self):
        self.redis_clt = Context.inst().coupon_redis

    def new(self, coupon_id, total, expire=None):
        """
        新建抢券活动

        :param coupon_id: 优惠券id
        :param total: 总数
        :param expire: 超时 sec or timedelta
        :return: code
        """
        key = self.key(coupon_id)
        self.redis_clt.set(key, total, ex=expire)
        logging.warning("create new coupon activity: key(%s) count(%s) expire(%s)",
                        key, total, expire)
        return E_SUCC

    @classmethod
    def key(cls, coupon_id):
        """
        获取key

        :param coupon_id: 优惠券id
        :return: key
        """
        return "coupon:%s" % coupon_id

    def is_success(self, coupon_id):
        """
        判断是否抢购成功

        :param coupon_id:
        :return: boolean, 剩余数量
        """
        key = self.key(coupon_id)
        count = self.redis_clt.decr(key)
        if count >= 0:
            return E_SUCC, count
        else:
            self.redis_clt.delete(key)
            logging.warning("delete coupon activity: cid(%s)", key)
            return E_COUPON_ACTIVITY_DONE, 0

    def update(self, coupon_id, params):
        """
        更新抢券活动

        :param coupon_id: 优惠券id
        :param params: 更新内容
        :return: code
        """
        key = self.key(coupon_id)
        if "total" in params:
            self.redis_clt.set(key, params["total"])
            logging.warning("update coupon activity: total(%s)", params["total"])
        if "expire" in params:
            self.redis_clt.expire(key, params["expire"])
            logging.warning("update coupon activity: expire(%s)", params["expire"])
        return E_SUCC, None

    def delete(self, coupon_id):
        """
        删除

        :param coupon_id: 优惠券id
        :return: boolean
        """
        logging.warning("delete coupon activity: key(%s)", self.key(coupon_id))
        self.redis_clt.delete(self.key(coupon_id))
        return E_SUCC, None

    def query(self, coupon_list):
        """
        查询余数

        :param coupon_list: 优惠券id列表
        :return: {优惠券id: 优惠券余数}
        """
        # return self.redis_clt.get(self.key(coupon_id)) or 0
        result = {}
        key = [self.key(i) for i in coupon_list]

        values = self.redis_clt.mget(key)
        for i in range(len(key)):
            result[coupon_list[i]] = values[i] or 0
        return result