使用python和redis实现分布式锁

2022-04-12  本文已影响0人  倔强青铜弟中弟

业务场景描述:

分布式锁具备的功能:

实现步骤:

唯一资源表示:

代码:

def redis_distributed_lock(lock_name: str):
    """
    redis分布式锁
    :param lock_name: redis中锁的名称
    :return:
    """
    def redis_function(func):
        def wrapper(self, *args, **kwargs):
            """
            High-availability operating mechanism based on redis
            :return: None
            """
            redis_model = RedisModel()
            lock_value = socket.gethostname() + "_" + str(threading.get_ident())
            # 没有注册上,休息后再尝试注册
            while True:
                try:
                    result = redis_model.set_ex_nx(key=lock_name, value=lock_value, seconds=60)
                    # 执行主体方法
                    func(*args, **kwargs)
                    # 获取锁的过期时间
                    ttl = redis_model.ttl(key=lock_name)
                    time.sleep(ttl if ttl > 1 else 1)
                except Exception as e:
                    self.logger.warning(
                        "Run redis_distributed_lock failed, cause: {}, traceback: {}".format(e, traceback.format_exc()))
                    time.sleep(5)

        return wrapper
    return redis_function

锁的续时间:

代码:

修饰器:redis_distributed_lock

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
=================================================
@Project -> File 
@IDE    :PyCharm
@Author :Desmond.zhan
@Date   :2021/12/7 3:07 下午
@Desc   :redis分布式锁,运行执行leader节点的服务器运行,其他的阻塞,以达到高可用
通过注解方式,灵活性更强
==================================================
"""
import ctypes
import inspect
import multiprocessing
import socket
import threading
import time
import traceback

# 自定义Redis Model.
from xxxxxx import RedisModel


def _async_raise(tid, exctype):
    """raises the exception, performs cleanup if needed"""
    tid = ctypes.c_long(tid)
    if not inspect.isclass(exctype):
        exctype = type(exctype)
    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
    if res == 0:
        raise ValueError("invalid thread id")
    elif res != 1:
        # """if it returns a number greater than one, you're in trouble,
        # and you should call it again with exc=NULL to revert the effect"""
        ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None)
        raise SystemError("PyThreadState_SetAsyncExc failed")


def _async_stop_children_process():
    """
    杀死主进程下所有的子进程
    :return:
    """
    children_process = multiprocessing.active_children()
    for process in children_process:
        process.terminate()


def redis_distributed_lock(lock_name: str):
    """
    redis分布式锁
    :param lock_name: redis中锁的名称
    :return:
    """

    def redis_function(func):
        def wrapper(self, *args, **kwargs):
            """
            High-availability operating mechanism based on redis
            :return: None
            """
            redis_model = RedisModel()
            lock_value = socket.gethostname() + "_" + str(threading.get_ident())
            # 没有注册上,休息后再尝试注册
            while True:
                try:
                    result = redis_model.set_ex_nx(key=lock_name, value=lock_value, seconds=60)
                    # 加锁成功后,判断是否该主机+线程用的这个锁,如果是,设置一个超时时间。否则仍旧等待加锁
                    self.logger.info("Redis set_nx result:{}".format(result))
                    self.logger.info(
                        "redis_model.get(lock_name) : {}, lock_value:{}".format(redis_model.get(lock_name), lock_value))

                    # 加锁成功
                    if result and redis_model.get(lock_name).decode(encoding="utf8") == lock_value:
                        # 获取到redis分布式锁,开启子线程,进行执行目标函数
                        t_func = threading.Thread(target=func, args=args, kwargs=kwargs)
                        t_func.start()
                        # 启动看门狗,lock续时
                        redis_model.lock_watchdog_timeout(key=lock_name, value=lock_value)
                        # 停止函数执行
                        _async_raise(tid=t_func.ident, exctype=SystemExit)
                        _async_stop_children_process()
                    # 获取锁的过期时间
                    ttl = redis_model.ttl(key=lock_name)
                    time.sleep(ttl if ttl > 1 else 1)
                except Exception as e:
                    self.logger.warning(
                        "Run redis_distributed_lock failed, cause: {}, traceback: {}".format(e, traceback.format_exc()))
                    time.sleep(5)

        return wrapper
    return redis_function

续时操作:watch_dog

    def lock_watchdog_timeout(self, key, value, seconds=30):
        self.logger.info("key:{} lock watch dog threading start work ".format(self.get_key(key)))
        try:
            self._lock_extend(key, value, seconds)
        except Exception as e:
            self.logger.warning("redis lock lock_watchdog_timeout error, error info :{}".format(e))

    def _lock_extend(self, key, value, lifetime):
        while True:
            try:
                self.logger.debug("watch dog extend key time, key:{}".format(self.get_key(key)))
                # 判断redis中还是否为本进程持有的锁
                redis_value = self.redis_client.get(name=self.get_key(key))
                if redis_value != value:
                    self.logger.warning(
                        "Watch dog warning, redis lock value is not acquired, will suspend function execution")
                    self.logger.warning("this value:{}, redis value".format(value, redis_value))
                    # watch dog也没意义了,直接返回吧
                    return
                result = self.redis_client.expire(name=self.get_key(key), time=lifetime)
                self.logger.debug("{} extend result : {}".format(self.get_key(key), str(result)))
                time.sleep(lifetime // 2)
            except Exception as e:
                self.logger.warning(
                    "Run _lock_extend failed, cause: {}, traceback: {}".format(e, traceback.format_exc()))
                time.sleep(5)

另外:

参考:

https://docs.python.org/zh-cn/3.7/library/ctypes.html#module-ctypes

https://docs.python.org/zh-cn/3.6/c-api/init.html?highlight=pythreadstate_setasyncexc

https://docs.python.org/3/library/multiprocessing.html

https://docs.python.org/zh-cn/3/library/signal.html?highlight=signal

上一篇下一篇

猜你喜欢

热点阅读