Distributed lock based on redis

@Autowired
private RedissonClient redissonClient;
RLock rLock = redissonClient.getLock(RedisKeyPrefix.TRADE_PRODUCT_IN_LOCK.getVal() + tradeFinancingProduct.getId());
try{
    //try to lock for 30 seconds
   if (rLock.tryLock(30, TimeUnit.SECONDS)) {
        //some
    }else{
        throw new SysException("tradeProductIn - acquire lock fail");    
    } 
}catch(InterruptedException e){
    throw new SysException("tradeProductIn - InterruptedException");
}finally {
    // release the distributed lock
    if (rLock.isLocked() && rLock.isHeldByCurrentThread()) {
        rLock.unlock(); log.info("tradeProductIn - lock release");
    }
}

isHeldByCurrentThread(): Query whether the current thread holds the lock 
isFair(): Determine whether the Lock is a fair lock 
isLocked(): Query whether the lock is held by any thread.

Good introductory blog: https://www.jianshu.com/p/cde0700f0128

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325426666&siteId=291194637