踩坑(6)Redisson调用unlockAsync方法释放锁失败

问题描述

通过redisson的lockAsync异步方法获取到锁之后,再业务执行完成后调用lock.unlockAsync()无法释放当前锁,导致后续的方法被阻塞

    public void asyncLock() {
        RLock lock = redissonClient.getLock("asyncLock");
        RFuture<Void> future = lock.lockAsync();
        future.whenComplete((res, exception) -> {
            System.out.println(Thread.currentThread().getName() + " 获取到锁 " + new Date());
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.unlockAsync().whenComplete((v, r) -> {
                System.out.println(Thread.currentThread().getName() + " 释放了锁 " + new Date());
            });
        });
        System.out.println(Thread.currentThread().getName() + " 其它操作..." + new Date());
    }
产生原因

释放锁的时候,当前如果没有传入线程id就会使用当前线程的id,由于当前方法是异步方法,和获取锁时的线程是不同的线程所以导致锁释放失败

    @Override
    public RFuture<Void> unlockAsync() {
        long threadId = Thread.currentThread().getId();
        return unlockAsync(threadId);
    }
解决方法

调用unlockAsync() 方法时传入获取锁线程的线程id

    public void asyncLock() {
        RLock lock = redissonClient.getLock("asyncLock");
        RFuture<Void> future = lock.lockAsync();
        long threadId = Thread.currentThread().getId();
        future.whenComplete((res, exception) -> {
            System.out.println(Thread.currentThread().getName() + " 获取到锁 " + new Date());
            try {
                Thread.sleep(10000L);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            lock.unlockAsync(threadId).whenComplete((v, r) -> {
                System.out.println(Thread.currentThread().getName() + " 释放了锁 " + new Date());
            });
        });
        System.out.println(Thread.currentThread().getName() + " 其它操作..." + new Date());
    }

你可能感兴趣的:(踩坑记录,java,开发语言,redis)