Java Code Examples for org.redisson.api.RLock#tryLock()

The following examples show how to use org.redisson.api.RLock#tryLock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test(expected = WriteRedisConnectionException.class)
public void testRedisFailed() throws IOException, InterruptedException {
    RedisRunner.RedisProcess master = new RedisRunner()
            .port(6377)
            .nosave()
            .randomDir()
            .run();

    Config config = new Config();
    config.useSingleServer().setAddress("redis://127.0.0.1:6377");
    RedissonClient redisson = Redisson.create(config);

    RLock lock = redisson.getLock("myLock");
    // kill RedisServer while main thread is sleeping.
    master.stop();
    Thread.sleep(3000);
    lock.tryLock(5, 10, TimeUnit.SECONDS);
}
 
Example 2
Source File: RedissonTest.java    From java-tutorial with MIT License 6 votes vote down vote up
@Test
public void test() throws InterruptedException {
    Config config = new Config();
    SingleServerConfig singleServerConfig = config.useSingleServer();
    singleServerConfig.setAddress(redssionProperties.getAddress());
    singleServerConfig.setPassword(redssionProperties.getPassword());

    RedissonClient redissonClient = RedisUtils.getInstance().getRedisson(config);
    RBucket<Object> rBucket = RedisUtils.getInstance().getRBucket(redissonClient, "key");

    System.out.println(rBucket.get());
    while (true) {
        RLock lock = redissonClient.getLock("com.lock");
        lock.tryLock(0, 1, TimeUnit.SECONDS);
        try {
            System.out.println("执行");
        } finally {
            lock.unlock();
        }
    }


}
 
Example 3
Source File: RedisLeaderElection.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Override
public final <T> T supplyIfLeader(final String lockName,
                                  final Supplier<T> supplier) {
    final RLock lock = redissonClient.getLock(lockName);
    T result = null;
    try {
        LOG.info("Waiting for becoming leader...");
        if (lock.tryLock(5, TimeUnit.SECONDS)) {
            LOG.info("Thread {} is leader for {} ", currentThread().getName(), lock.getName());
            try {
                result = supplier.get();
            } finally {
                if (lock.isHeldByCurrentThread()) {
                    lock.unlock();
                    LOG.info("Released leader-election lock {}", currentThread().getName(), lock.getName());
                }
            }
        }
    } catch (final InterruptedException e) {
        LOG.error(e.getMessage(), e);
    }
    return result;
}
 
Example 4
Source File: RedissLockDemo.java    From spring-boot-seckill with GNU General Public License v2.0 6 votes vote down vote up
/**
    * 可重入锁(Reentrant Lock) 
    * Redisson的分布式可重入锁RLock Java对象实现了java.util.concurrent.locks.Lock接口,同时还支持自动过期解锁
    * @param redisson
    */
public void testReentrantLock(RedissonClient redisson) {
	RLock lock = redisson.getLock("anyLock");
	try {
		// 1. 最常见的使用方法
		// lock.lock();
		// 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁
		// lock.lock(10, TimeUnit.SECONDS);
		// 3. 尝试加锁,最多等待3秒,上锁以后10秒自动解锁
		boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
		if (res) { // 成功
			// do your business
		}
	} catch (InterruptedException e) {
		e.printStackTrace();
	} finally {
		lock.unlock();
	}
}
 
Example 5
Source File: RedissonDistributedLocker.java    From dk-foundation with GNU Lesser General Public License v2.1 5 votes vote down vote up
public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
    RLock lock = redissonClient.getLock(lockKey);
    try {
        return lock.tryLock(waitTime, leaseTime, unit);
    } catch (InterruptedException e) {
        return false;
    }
}
 
Example 6
Source File: RedissonDistributedLocker.java    From SpringBoot2.0 with Apache License 2.0 5 votes vote down vote up
@Override
public boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
    RLock lock = redissonClient.getLock(lockKey);
    try {
        return lock.tryLock(waitTime, leaseTime, unit);
    } catch (InterruptedException e) {
        return false;
    }
}
 
Example 7
Source File: DataHandler.java    From kkbinlog with Apache License 2.0 5 votes vote down vote up
private void doRunWithLock() {
    RLock rLock = redissonClient.getLock(dataKeyLock);
    EventBaseDTO dto;
    boolean lockRes = false;
    try {
        // 尝试加锁,最多等待50ms(防止过多线程等待),上锁以后6个小时自动解锁(防止redis队列太长,当前拿到锁的线程处理时间过长)
        lockRes = rLock.tryLock(50, 6 * 3600 * 1000, TimeUnit.MILLISECONDS);
        if (!lockRes) {
            return;
        }
        DATA_KEY_IN_PROCESS.add(dataKey);
        //拿到锁之后再获取队列
        RQueue<EventBaseDTO> queue = redissonClient.getQueue(dataKey);
        if (!queue.isExists() || queue.isEmpty()) {
            return;
        }
        //拿到锁且 队列不为空 进入
        while ((dto = queue.peek()) != null) {
            //处理完毕,把数据从队列摘除
            boolean handleRes = doHandleWithLock(dto, 0);
            if (handleRes) {
                queue.remove();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.severe("接收处理数据失败:" + e.toString());
    } finally {
        //forceUnlock是可以释放别的线程拿到的锁的,需要判断是否是当前线程持有的锁
        if (lockRes) {
            rLock.forceUnlock();
            rLock.delete();
            DATA_KEY_IN_PROCESS.remove(dataKey);
        }
    }
}
 
Example 8
Source File: RedissonDistributedLocker.java    From lion with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试加锁
 *
 * @param lockKey   锁的key值
 * @param unit      时间单位
 * @param waitTime  等待时间
 * @param leaseTime 加锁时间
 * @return 是否拿到标志
 */
@Override
public boolean tryLock(String lockKey, TimeUnit unit, long waitTime, long leaseTime) {
    RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey);
    try {
        return lock.tryLock(waitTime, leaseTime, unit);
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
        return false;
    }
}
 
Example 9
Source File: RedisLockHelper.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试获取锁
 * @param lockKey
 * @param waitTime 最多等待时间
 * @param leaseTime 上锁后自动释放锁时间
 * @return
 */
public  boolean tryLock(String lockKey, int waitTime, int leaseTime) {
    RLock lock = redissonClient.getLock(lockKey);
    try {
        return lock.tryLock(waitTime, leaseTime, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        return false;
    }
}
 
Example 10
Source File: RedissonDistributedLocker.java    From lion with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试加锁
 *
 * @param lockKey   锁的key值
 * @param waitTime  等待时间
 * @param leaseTime 加锁时间
 * @return 是否拿到标志
 */
@Override
public boolean tryLock(String lockKey, long waitTime, long leaseTime) {
    RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey);
    try {
        return lock.tryLock(waitTime, leaseTime, TIME_UNIT);
    } catch (InterruptedException e) {
        return false;
    }
}
 
Example 11
Source File: InitialCodeServiceImpl.java    From short-url with Apache License 2.0 5 votes vote down vote up
/**
 * 此方法用于获取一个 initial code,方法中使用了基于 redis 的分布式锁,
 * 用于防止不同的机器获取相同的 initial code。考虑这样一种情况,某台机器
 * 服务崩溃,这台机器使用的 initial code 对应的 url_mapping 表还有空间
 * 可用。如果 initial_code 表中无新的 initial code 可分配,那么新的服务
 * 将会去"捡漏",尝试获取崩溃的服务所使用的 initial code。当多个服务竞争
 * 同一个 initial code 时,若不加控制,则会导致不同的服务获得了同一个
 * initial code。虽然多个服务使用同一个 initial code 并不会导致错误发生,
 * 但在程序设计上,建议一个服务对应一个 initial code。
 *
 *
 * @return initial code
 * @throws NoMoreInitialCodeException
 * @throws InterruptedException
 * @throws FailToAcquireDistributeLockException
 */
private Long getInitialCode() throws NoMoreInitialCodeException,
        InterruptedException, FailToAcquireDistributeLockException {

    RLock lock = redissonClient.getLock(DISTRIBUTED_LOCK_NAME);
    if (!lock.tryLock(3, 30, TimeUnit.SECONDS)) {
        throw new FailToAcquireDistributeLockException();
    }

    try {
        initialCode = initialCodeDao.insert();
        if (initialCode <= MAX_INITIAL_CODE) {
            initialCodeCache.addInUseCache(initialCode);
            return initialCode;
        }

        Set<String> inUseInitialCodes = initialCodeCache.readInUseCache();
        for (Long i = 0L; i < MAX_INITIAL_CODE; i++) {
            if (inUseInitialCodes.contains(i.toString())) {
                continue;
            }

            if (urlMappingDao.hasMoreSpace(i)) {
                initialCodeCache.addInUseCache(i);
                return i;
            }
        }
    } finally {
        lock.unlock();
    }

    throw new NoMoreInitialCodeException("no available initial code");
}
 
Example 12
Source File: RedissonDistributedLock.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public RLock tryLock(String key, long waitTime, long leaseTime, TimeUnit unit, boolean isFair) throws InterruptedException {
    RLock lock = getLock(key, isFair);
    if (lock.tryLock(waitTime, leaseTime, unit)) {
        return lock;
    }
    return null;
}
 
Example 13
Source File: SystemReadyListener.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    RLock lock = redisson.getLock(StringHelper.join(
            PersistentConstant.EXTENSIONPOINT_CHANGE_LOCK,
            NamingConstant
                    .shortName(point.getListener())));
    if (lock.tryLock() && lock.isHeldByCurrentThread()) {
        try {
            doRun();
        } finally {
            lock.unlock();
        }
    }
}
 
Example 14
Source File: SysJobActuator.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试获取锁
 * @param rlock
 * @param key
 * @return true 获取成功  false 获取失败
 */
private boolean tryLock(RLock rlock, String key) {
    try {
        Boolean lock = rlock.tryLock(JOB_KEY_WAIT_TIME, JOB_KEY_LOCK_TIME, TimeUnit.MILLISECONDS);
        if (!lock) {
            log.warn("job:{},lock:{} 被占用!", jobSchedule.getFdId(), key);
            return false;
        }
    } catch (InterruptedException e) {
        log.error("获取锁异常,{}", jobSchedule.getFdId(), e);
        return false;
    }
    return true;
}
 
Example 15
Source File: RedisLock.java    From conductor with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param lockId resource to lock on
 * @param timeToTry blocks up to timeToTry duration in attempt to acquire the lock
 * @param leaseTime Lock lease expiration duration. Redisson default is -1, meaning it holds the lock until explicitly unlocked.
 * @param unit time unit
 * @return
 */
@Override
public boolean acquireLock(String lockId, long timeToTry, long leaseTime, TimeUnit unit) {
    RLock lock = redisson.getLock(parseLockId(lockId));
    try {
        return lock.tryLock(timeToTry, leaseTime, unit);
    } catch (Exception e) {
        return handleAcquireLockFailure(lockId, e);
    }
}
 
Example 16
Source File: RedisLock.java    From Limiter with Apache License 2.0 4 votes vote down vote up
@Override
public boolean lock(Object key) {
    RLock rLock = redisson.getLock(key.toString());
    return rLock.tryLock();
}
 
Example 17
Source File: RedissonLocker.java    From SpringBoot-Home with Apache License 2.0 4 votes vote down vote up
public boolean tryLock(String lockKey, long waitTime, long leaseTime,
                       TimeUnit unit) throws InterruptedException{
    RLock lock = redissonClient.getLock(lockKey);
    return lock.tryLock(waitTime, leaseTime, unit);
}
 
Example 18
Source File: FairLockStrategy.java    From fast-family-master with Apache License 2.0 4 votes vote down vote up
@Override
public RLock tryLock(LockInfo lockInfo) throws InterruptedException {
    RLock lock = redissonClient.getLock(lockInfo.getLockName());
    boolean isAcquiringLock = lock.tryLock(lockInfo.getWaitTime(),lockInfo.getLockTime(), TimeUnit.MILLISECONDS);
    return isAcquiringLock == true ? lock : null;
}
 
Example 19
Source File: RedisAtom.java    From Milkomeda with MIT License 4 votes vote down vote up
@Override
public AtomLockInfo tryLock(String keyPath, AtomLockType type, boolean readOnly) {
    RLock lock = getLock(keyPath, type, readOnly);
    boolean isLocked = lock.tryLock();
    return AtomLockInfo.builder().isLocked(isLocked).lock(lock).build();
}
 
Example 20
Source File: RedissonDistributedLocker.java    From lion with Apache License 2.0 2 votes vote down vote up
/**
 * 尝试加锁
 *
 * 马上返回,拿到lock就返回true,不然返回false
 * 带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false
 *
 * @param lockKey 锁的key值
 * @return 是否拿到
 */
@Override
public boolean tryLock(String lockKey) {
    RLock lock = redissonClient.getLock(KEY_PREFIX + lockKey);
    return lock.tryLock();
}