首页 > 其他 > 详细

redis分布式锁-自动超时锁

时间:2018-07-22 13:33:41      阅读:459      评论:0      收藏:0      [点我收藏+]

1、加锁代码结构

2、解锁代码结构

3、java实例

4、测试类

5、测试日志

 

加锁代码结构

def acquire_lock_with_timeout(conn,lockname,acquire_timeout,lock_timeout)
    identifer=uuid.uuid4
    lockname=‘lock:‘+lockname
    repeat_end_time=current_time()+acquire_timeout
    
    while current_time<repeat_end_time
        if conn.setnx(lockname,identifer)
            conn.expire(lockname,lock_timeout)
            return identifer
        elif not conn.ttl(lockname)
            conn.expire(lockname,lock_timeout)
        time.sleep(0.001)
    return false

 

解锁代码结构

def release_loc(conn,lockname,identifer)
    pipe=conn.pipeline(true)
    lockname=‘lock:‘+lockname
    while True
        try:
            pipe.watch(lockname)
            if pipe.get(lockname) == identifer   // 检查进程是否仍然是有锁,若未持有锁,则返回false
                pipe.multi()
                pipe.delete(lockname)
                pipe.execute
                return true
            pipe.unwatch()
            break
        except redis.exceptions.WatchError
            pass    // 有其他客户端修改了锁,重试
    return False

 

redis分布式锁-自动超时锁

原文:https://www.cnblogs.com/jiangtao1218/p/9349788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!