Python---分布式共享锁实现

# -*- coding: utf-8 -*-

# @Author   : lws
# @Time     : 2018/11/21 14:36
# @describe : 分布式锁的API封装


import logging, os, time
from kazoo.client import KazooClient
from kazoo.client import KazooState
from kazoo.recipe.lock import Lock

logging.basicConfig()


class ZooKeeperLock():
    def __init__(self, hosts, lock_path, lock_name, lock_value, timeout=1):
        self.hosts = hosts
        self.zk_client = None
        self.timeout = timeout
        self.name = lock_name
        self.lock_path = "PolicyCtrlCent/" + lock_path + "/" + lock_name
        self.lock_value = lock_value
        self.lock_handle = None

        self.create_lock()

    def create_lock(self):
        try:
            self.zk_client = KazooClient(hosts=self.hosts, timeout=self.timeout)

            @self.zk_client.add_listener
            def my_listener(state):
                if state == KazooState.LOST:
                    print("LOST")
                elif state == KazooState.SUSPENDED:
                    print("SUSPENDED")
                else:
                    print("Connected")

            self.zk_client.start(timeout=self.timeout)
            self.add_zk_auth()

        except Exception, ex:
            self.init_ret = False
            self.err_str = "Create KazooClient failed! Exception: %s" % str(ex)

        try:
            print self.lock_path
            self.lock_handle = Lock(self.zk_client, self.lock_path)
            self.zk_client.set(self.lock_path, self.lock_value)
        except Exception, ex:
            self.init_ret = False
            self.err_str = "Create lock failed! Exception: %s" % str(ex)

        from kazoo.security import make_digest_acl
        client = self.zk_client
        acl = make_digest_acl('pcm', 'pcm', all=True)
        try:
            client.set_acls(self.lock_path, [acl])
        finally:
            print("set KazooClient acl SUCCESS!")

    def destroy_lock(self):
        # self.release()

        if self.zk_client != None:
            self.zk_client.stop()
            self.zk_client = None

    def acquire(self, blocking=True, timeout=None):
        if self.lock_handle == None:
            return None

        try:
            return self.lock_handle.acquire(blocking=blocking, timeout=timeout)
        except Exception, ex:
            self.err_str = "Acquire lock failed! Exception: %s" % str(ex)
            return None

    def release(self):
        if self.lock_handle == None:
            return None
        return self.lock_handle.release()

    def __del__(self):
        self.destroy_lock()

    def _makeAuth(self, *args, **kwargs):
        from kazoo.security import make_digest_acl
        return make_digest_acl(*args, **kwargs)

    def add_zk_auth(self):
        username = "pcm"
        password = "pcm"
        digest_auth = "%s:%s" % (username, password)
        acl = self._makeAuth(username, password, all=True)
        self.zk_client.add_auth("digest", digest_auth)
        self.zk_client.default_acl = (acl,)
        print("add zk_auth SUCCESS!")


def main():
    zookeeper_hosts = "127.0.0.1:2181"
    lock_name = "test"
    pid = str(os.getpid())
    lock = ZooKeeperLock(zookeeper_hosts, "asdqe", lock_name, pid)
    print "a"

    ret = lock.acquire(timeout=3)
    print ret
    print "b"
    if not ret:
        return

    for i in range(1, 10):
        time.sleep(1)
        print i
    lock.release()


if __name__ == "__main__":
    try:
        while True:
            main()
            time.sleep(1)
    except Exception, ex:
        print "Ocurred Exception: %s" % str(ex)
        quit()

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
分布式锁是为了保证在分布式系统中的多个节点之间对共享资源的访问的互斥性。Redis是一个高性能的键值存储数据库,支持多种数据结构,其中包括有序集合和原子操作等特性,可以用来实现分布式锁。 下面是一种使用Redis实现分布式锁的方法: 1. 生成唯一的锁标识符,可以使用UUID等方式生成。 2. 尝试通过Redis的SET命令将锁标识符作为键,设置到Redis中,同时设置过期时间,避免死锁的情况。如果SET命令返回成功,则表示获取到了锁,可以执行业务逻辑。 3. 如果SET命令返回失败,表示锁已经被其他节点占用,需要等待一段时间后重新尝试获取锁,可以使用sleep等方式避免频繁重试。 4. 执行完业务逻辑后,需要通过DEL命令将锁标识符从Redis中删除,释放锁资源。 下面是一个使用Python实现的Redis分布式锁的示例代码: ```python import redis import uuid import time class RedisLock: def __init__(self, redis_client, key, expire=10): self.redis_client = redis_client self.key = key self.expire = expire self.value = str(uuid.uuid4()) def acquire(self): while True: if self.redis_client.set(self.key, self.value, nx=True, ex=self.expire): return True time.sleep(0.1) def release(self): script = ''' if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1]) else return 0 end ''' self.redis_client.eval(script, 1, self.key, self.value) ``` 在上面的示例代码中,使用了Redis的NX选项,表示只有在键不存在的情况下才会设置成功。在释放锁资源的时候,使用了Redis的EVAL命令,可以保证在多线程或者多进程的情况下,释放的锁资源是自己所持有的。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值