ZBLOG

python 实现 redis 分布式锁

好的,实现Redis分布式锁的Python代码如下:

import redis
import time

class RedisLock:
    def __init__(self, redis_conn, lock_key, timeout=10):
        self.redis = redis_conn
        self.lock_key = lock_key
        self.timeout = timeout
        self.identifier = None
    
    def acquire_lock(self):
        identifier = str(time.time())
        
        while True:
            if self.redis.setnx(self.lock_key, identifier):
                self.identifier = identifier
                return True
            
            current_value = self.redis.get(self.lock_key)
            
            if not current_value:
                continue
            
            expiration_time = float(current_value) + self.timeout
            
            if time.time() > expiration_time:
                old_value = self.redis.getset(self.lock_key, identifier)
                
                if old_value == current_value:
                    self.identifier = identifier
                    return True
                
            time.sleep(0.1)
            
    def release_lock(self):
        pipe = self.redis.pipeline(True)
        
        while True:
            try:
                pipe.watch(self.lock_key)
                current_value = pipe.get(self.lock_key)
                
                if not current_value:
                    break
                
                if current_value.decode('utf-8') == self.identifier:
                    pipe.multi()
                    pipe.delete(self.lock_key)
                    pipe.execute()
                    
                    return True
                
                pipe.unwatch()
                
            except redis.exceptions.WatchError:
                pass
            
    def __enter__(self):
        result = self.acquire_lock()
        
        if not result:
            raise Exception("Could not obtain lock")
        
        return result
    
    def __exit__(self, type_, value, traceback):
        result = self.release_lock()

使用方法如下所示:

redis_conn = redis.Redis(host='localhost', port=6379)

with RedisLock(redis_conn, 'my_lock'):
    # 在此处执行需要加锁的代码

希望能够帮助到您。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=3195

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?