django分布式锁

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

利用redis做分布式锁:

import redis

DEFAULT_EXPIRES = 60
client = redis.Redis(connection_pool=redis.BlockingConnectionPool(max_connections=50,
                                                                  host=settings.REDIS_IP,
                                                                  password=settings.REDIS_PASSWORD,
                                                                  port=6379, db=settings.REDIS_DB))


def acquire_lock(key, timeout=60):
    if client.setnx(key, 1):
        client.expire(key, timeout)
        return True
    return False


def release_lock(key):
    client.delete(key)

django事物:

def give_product(steam_uid, ids):
    """
    购买
    :param ids:
    :param steam_uid:
    :return:
    """
    result = False
    try:
        with transaction.atomic():
            size = ProductTrade.objects.filter(id__in=ids, status=IN_STORAGE).update(status=DONE,
                                                                                     last_updated=datetime.now())
            assert size == len(ids)
            for trade_id in ids:
                trade = ProductTrade.objects.filter(id=trade_id).first()
                if trade:
                    trade.id = None
                    trade.status = ON_OFFEER
                    trade.steam_uid = steam_uid
                    trade.last_trade_id = trade_id
                    trade.save()
                    result = True
    except BaseException as e:

        client.captureException()

    return result

 

转载于:https://my.oschina.net/jamescasta/blog/1544206

你可能感兴趣的:(django分布式锁)