redis分布式锁-自动超时锁

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

猜你喜欢

转载自www.cnblogs.com/jiangtao1218/p/9349788.html