Redis setnx use in atomic operations to ensure that the resources

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/u011510825/article/details/81064106

In the multi-process ( thread time) access to shared resources, to ensure that all are not the same as the other processes (threads) at the same time access to resources. Atomic operation (atomic operation) need not be synchronized, which is commonplace multithreaded programming. Refers to the so-called atomic operations are not thread scheduling interrupted operation mechanism; Once this operation, it runs to completion, without any intermediate context switch (switching to another thread).


The latest have the business needs, so wrote a decorator, with a view to ensure that only one person has the same resource operating authority. talk is cheap, show you the code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by guozhihua12
# 实现对view的锁操作,确保当前的view只有一个人操作
import functools
from redis import RedisCache

redis_cache = RedisCache()


def view_lock():
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 要求第一个参数为资源的id
            key = 'view_name_{}_id_{}'.format(getattr(func, '__name__'), args[0])
            # 尝试获取锁
            result = redis_cache.setnx(key, '1')
            if result:
                try:
                    data = func(*args, **kwargs)
                except:
                    raise
                finally:
                    # 释放锁
                    redis_cache.delete(key)
                return data
            # todo 考虑是否需要等待两秒后再次尝试获取锁
            raise Exception(message='目前无法操作该资源,稍后再试!')

        return wrapper

    return decorator


@view_lock()
def test(id):
    print(id)


if __name__ == '__main__':
    test(12345)

Logic code is relatively simple, as long as understand the point of python decorators principle classmates, are not difficult to understand. That under the principle, using redis in setnx property, if setnx returns 1, indicating successfully acquiring the lock, you can view the corresponding operation; on the contrary, returns 0, indicating that the resource was being edited, can not be used. After the operation is complete, no matter there is no abnormality, should release the lock.


Guess you like

Origin blog.csdn.net/u011510825/article/details/81064106