org.redisson.api.RLock Java Examples

The following examples show how to use org.redisson.api.RLock. 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: RedisLockTest.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Test
public void testLockReentry() throws InterruptedException {
    redisson.getKeys().flushall();
    String lockId = "abcd-1234";
    boolean isLocked = redisLock.acquireLock(lockId, 1000, 60000, TimeUnit.MILLISECONDS);
    assertTrue(isLocked);

    Thread.sleep(1000);

    // get the lock back
    isLocked = redisLock.acquireLock(lockId, 1000, 1000, TimeUnit.MILLISECONDS);
    assertTrue(isLocked);

    RLock lock = redisson.getLock(lockId);
    assertTrue(isLocked);
}
 
Example #2
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 #3
Source File: RedissonCache.java    From redisson with Apache License 2.0 6 votes vote down vote up
public <T> T get(Object key, Callable<T> valueLoader) {
    Object value = map.get(key);
    if (value == null) {
        addCacheMiss();
        RLock lock = map.getLock(key);
        lock.lock();
        try {
            value = map.get(key);
            if (value == null) {
                value = putValue(key, valueLoader, value);
            }
        } finally {
            lock.unlock();
        }
    } else {
        addCacheHit();
    }
    
    return (T) fromStoreValue(value);
}
 
Example #4
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrency_SingleInstance() throws InterruptedException {
    final AtomicInteger lockedCounter = new AtomicInteger();

    final Random r = new SecureRandom();
    int iterations = 15;
    testSingleInstanceConcurrency(iterations, rc -> {
        RReadWriteLock rwlock = rc.getReadWriteLock("testConcurrency_SingleInstance");
        RLock lock;
        if (r.nextBoolean()) {
            lock = rwlock.writeLock();
        } else {
            lock = rwlock.readLock();
        }
        lock.lock();
        lockedCounter.incrementAndGet();
        lock.unlock();
    });

    Assert.assertEquals(iterations, lockedCounter.get());
}
 
Example #5
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testConcurrency_MultiInstance() throws InterruptedException {
    int iterations = 100;
    final AtomicInteger lockedCounter = new AtomicInteger();

    final Random r = new SecureRandom();
    testMultiInstanceConcurrency(iterations, rc -> {
        RReadWriteLock rwlock = rc.getReadWriteLock("testConcurrency_MultiInstance2");
        RLock lock;
        if (r.nextBoolean()) {
            lock = rwlock.writeLock();
        } else {
            lock = rwlock.readLock();
        }
        lock.lock();
        lockedCounter.incrementAndGet();
        lock.unlock();
    });

    Assert.assertEquals(iterations, lockedCounter.get());
}
 
Example #6
Source File: BaseTransactionalMap.java    From redisson with Apache License 2.0 6 votes vote down vote up
protected <R> void executeLocked(RPromise<R> promise, Runnable runnable, Collection<K> keys) {
    List<RLock> locks = new ArrayList<>(keys.size());
    for (K key : keys) {
        RLock lock = getLock(key);
        locks.add(lock);
    }
    RedissonMultiLock multiLock = new RedissonMultiLock(locks.toArray(new RLock[locks.size()]));
    long threadId = Thread.currentThread().getId();
    multiLock.lockAsync(timeout, TimeUnit.MILLISECONDS).onComplete((res, e) -> {
        if (e == null) {
            runnable.run();
        } else {
            multiLock.unlockAsync(threadId);
            promise.tryFailure(e);
        }
    });
}
 
Example #7
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 #8
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHoldCount() {
    RLock lock = redisson.getLock("lock");
    Assert.assertEquals(0, lock.getHoldCount());
    lock.lock();
    Assert.assertEquals(1, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(0, lock.getHoldCount());

    lock.lock();
    lock.lock();
    Assert.assertEquals(2, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(1, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(0, lock.getHoldCount());
}
 
Example #9
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 #10
Source File: RedissonFairLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpire() throws InterruptedException {
    RLock lock = redisson.getFairLock("lock");
    lock.lock(2, TimeUnit.SECONDS);

    final long startTime = System.currentTimeMillis();
    Thread t = new Thread() {
        public void run() {
            RLock lock1 = redisson.getFairLock("lock");
            lock1.lock();

            long spendTime = System.currentTimeMillis() - startTime;
            System.out.println(spendTime);
            Assert.assertTrue(spendTime < 2020);
            lock1.unlock();
        };
    };

    t.start();
    t.join();

    lock.unlock();
}
 
Example #11
Source File: timingCloseOrderTask.java    From mmall20180107 with Apache License 2.0 6 votes vote down vote up
private void closeOrderTaskV3(){

         RLock rLock = redissonManage.getRedisson().getLock(Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);

         Boolean lock = false;

        try {
            if(lock = rLock.tryLock(0,5,TimeUnit.SECONDS)){
                log.info("获取到分布式锁:{},线程:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK,Thread.currentThread().getName());
                int hour = Integer.parseInt(PropertiesUtil.getProperty("close.order.task.time.hour"));
                iOrderService.closeOrder(hour);
            }else {
                log.info("没有获取到分布式锁");
            }
        } catch (InterruptedException e) {
            log.info("没有获取到分布式锁",e);
        } finally {
            if(!lock){
                return;
            }
            log.info("===释放分布式锁:{}",Const.REDIS_LOCK.CLOSE_ORDER_TASK_LOCK);
            rLock.unlock();
        }


    }
 
Example #12
Source File: RedissLockDemo.java    From spring-boot-seckill with GNU General Public License v2.0 6 votes vote down vote up
/**
 *  红锁(RedLock)
 *  Redisson的RedissonRedLock对象实现了Redlock介绍的加锁算法。该对象也可以用来将多个RLock对象关联为一个红锁,每个RLock对象实例可以来自于不同的Redisson实例
 * @param redisson1
 * @param redisson2
 * @param redisson3
 */
public void testRedLock(RedissonClient redisson1,RedissonClient redisson2, RedissonClient redisson3){  
    RLock lock1 = redisson1.getLock("lock1");  
    RLock lock2 = redisson2.getLock("lock2");  
    RLock lock3 = redisson3.getLock("lock3");  
    RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);  
    try {  
        // 同时加锁:lock1 lock2 lock3, 红锁在大部分节点上加锁成功就算成功。  
        lock.lock();  
        // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁  
        boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);  
        if (res) {
			// do your business
		}
    } catch (InterruptedException e) {  
        e.printStackTrace();  
    } finally {  
        lock.unlock();  
    }  
}
 
Example #13
Source File: RedissonFairLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetHoldCount() {
    RLock lock = redisson.getFairLock("lock");
    Assert.assertEquals(0, lock.getHoldCount());
    lock.lock();
    Assert.assertEquals(1, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(0, lock.getHoldCount());

    lock.lock();
    lock.lock();
    Assert.assertEquals(2, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(1, lock.getHoldCount());
    lock.unlock();
    Assert.assertEquals(0, lock.getHoldCount());
}
 
Example #14
Source File: RedissonRedLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testLockSuccess() throws IOException, InterruptedException {
    RedisProcess redis1 = redisTestMultilockInstance();
    RedisProcess redis2 = redisTestMultilockInstance();
    
    RedissonClient client1 = createClient(redis1.getRedisServerAddressAndPort());
    RedissonClient client2 = createClient(redis2.getRedisServerAddressAndPort());
    
    RLock lock1 = client1.getLock("lock1");
    RLock lock2 = client1.getLock("lock2");
    RLock lock3 = client2.getLock("lock3");
    
    testLock(lock1, lock2, lock3, lock1);
    testLock(lock1, lock2, lock3, lock2);
    testLock(lock1, lock2, lock3, lock3);
    
    client1.shutdown();
    client2.shutdown();
    
    assertThat(redis1.stop()).isEqualTo(0);
    assertThat(redis2.stop()).isEqualTo(0);
}
 
Example #15
Source File: RedissonMultiLock.java    From redisson with Apache License 2.0 6 votes vote down vote up
protected RFuture<Void> unlockInnerAsync(Collection<RLock> locks, long threadId) {
    if (locks.isEmpty()) {
        return RedissonPromise.newSucceededFuture(null);
    }
    
    RPromise<Void> result = new RedissonPromise<Void>();
    AtomicInteger counter = new AtomicInteger(locks.size());
    for (RLock lock : locks) {
        lock.unlockAsync(threadId).onComplete((res, e) -> {
            if (e != null) {
                result.tryFailure(e);
                return;
            }
            
            if (counter.decrementAndGet() == 0) {
                result.trySuccess(null);
            }
        });
    }
    return result;
}
 
Example #16
Source File: RedisLockHelper.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 尝试获取锁
 * @param lockKey
 * @param unit 时间单位
 * @param waitTime 最多等待时间
 * @param leaseTime 上锁后自动释放锁时间
 * @return
 */
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 #17
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 #18
Source File: ShopifyJacksonDecoder.java    From shopify-api-java-wrapper with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(Response response, Type type) throws IOException
{
    Collection<String> shopifyApiCallLimitHeader = response.headers().get("HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT");

    String[] callLimitValues = shopifyApiCallLimitHeader.iterator().next().split("/");

    if(callLimitValues[0] != null && callLimitValues[0] != "")
    {
        Long createdCalls = Long.parseLong(callLimitValues[0]);

        Long remainingCalls = _shopifyRedissonManager.calculateAvalableCredits(createdCalls);

        RedissonClient redisson = _shopifyRedissonManager.getRedissonClient();

        // Lock per shopify store. The lock is distributed, so it will work for multiple threads and applications.
        RLock lock = redisson.getLock(_shopifyRedissonManager.getMyShopifyUrl());

        RAtomicLong remainingCreditsAtomic = redisson.getAtomicLong(_shopifyRedissonManager.getRemainingCreditsKey());
        RAtomicLong lastRequestTimeAtomic = redisson.getAtomicLong(_shopifyRedissonManager.getLastRequestTimeKey());

        remainingCreditsAtomic.set(remainingCalls);
        lastRequestTimeAtomic.set(System.currentTimeMillis());

        lock.unlock();
    }

    return super.decode(response, type);
}
 
Example #19
Source File: SystemReadyListener.java    From mPass 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 #20
Source File: RedissonFairLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsLocked() {
    RLock lock = redisson.getFairLock("lock");
    Assert.assertFalse(lock.isLocked());
    lock.lock();
    Assert.assertTrue(lock.isLocked());
    lock.unlock();
    Assert.assertFalse(lock.isLocked());
}
 
Example #21
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testName() throws InterruptedException, ExecutionException, TimeoutException {
    ExecutorService service = Executors.newFixedThreadPool(10);
    RReadWriteLock rwlock = redisson.getReadWriteLock("{test}:abc:key");
    RLock rlock = rwlock.readLock();

    List<Callable<Void>> callables = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
      callables.add(() -> {
        for (int j = 0; j < 10; j++) {
          rlock.lock();
          try {
          } finally {
            rlock.unlock();
          }
        }
        return null;
      });
    }

    List<Future<Void>> futures = service.invokeAll(callables);
    for (Future<Void> future : futures) {
        assertThatCode(future::get).doesNotThrowAnyException();
    }

    service.shutdown();
    assertThat(service.awaitTermination(1, TimeUnit.MINUTES)).isTrue();
}
 
Example #22
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 #23
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsHeldByCurrentThread() {
    RReadWriteLock rwlock = redisson.getReadWriteLock("lock");
    RLock lock = rwlock.readLock();
    Assert.assertFalse(lock.isHeldByCurrentThread());
    lock.lock();
    Assert.assertTrue(lock.isHeldByCurrentThread());
    lock.unlock();
    Assert.assertFalse(lock.isHeldByCurrentThread());
}
 
Example #24
Source File: RedissonMap.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void loadValue(K key, RPromise<V> result, boolean replaceValue) {
    RLock lock = getLock(key);
    long threadId = Thread.currentThread().getId();
    lock.lockAsync(threadId).onComplete((res, e) -> {
        if (e != null) {
            lock.unlockAsync(threadId);
            result.tryFailure(e);
            return;
        }
        
        if (replaceValue) {
            loadValue(key, result, lock, threadId);
            return;
        }
        
        getOperationAsync(key).onComplete((r, ex) -> {
            if (ex != null) {
                lock.unlockAsync(threadId);
                result.tryFailure(ex);
                return;
            }
            
            if (r != null) {
                unlock(result, lock, threadId, r);
                return;
            }
            
            loadValue(key, result, lock, threadId);
        });
    });
}
 
Example #25
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testWR() throws InterruptedException {
    RReadWriteLock rw = redisson.getReadWriteLock("my_read_write_lock");
    RLock writeLock = rw.writeLock();
    writeLock.lock();
    
    rw.readLock().lock();
    assertThat(writeLock.isLocked()).isTrue();
    rw.readLock().unlock();
    
    assertThat(writeLock.isLocked()).isTrue();
    writeLock.unlock();
    assertThat(writeLock.isLocked()).isFalse();
}
 
Example #26
Source File: SimpleLockDelegate.java    From fast-family-master with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
    Method method = invocation.getMethod();
    lockStrategy = matchLockStrategy(method);
    LockInfo lockInfo = new LockInfo();
    RLock rLock = null;
    try {
        rLock = lockStrategy.tryLock(lockInfo);
        return invocation.proceed();
    } catch (Exception e) {
        throw e;
    } finally {
        lockStrategy.unlock(rLock);
    }
}
 
Example #27
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrencyLoop_MultiInstance() throws InterruptedException {
    final int iterations = 100;
    final AtomicInteger lockedCounter = new AtomicInteger();

    final Random r = new SecureRandom();
    testMultiInstanceConcurrency(16, rc -> {
        for (int i = 0; i < iterations; i++) {
            boolean useWriteLock = r.nextBoolean();
            RReadWriteLock rwlock = rc.getReadWriteLock("testConcurrency_MultiInstance1");
            RLock lock;
            if (useWriteLock) {
                lock = rwlock.writeLock();
            } else {
                lock = rwlock.readLock();
            }
            lock.lock();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lockedCounter.incrementAndGet();
            rwlock = rc.getReadWriteLock("testConcurrency_MultiInstance1");
            if (useWriteLock) {
                lock = rwlock.writeLock();
            } else {
                lock = rwlock.readLock();
            }
            lock.unlock();
        }
    });

    Assert.assertEquals(16 * iterations, lockedCounter.get());
}
 
Example #28
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testInCluster() throws Exception {
    RedisRunner master1 = new RedisRunner().port(6890).randomDir().nosave();
    RedisRunner master2 = new RedisRunner().port(6891).randomDir().nosave();
    RedisRunner master3 = new RedisRunner().port(6892).randomDir().nosave();
    RedisRunner slave1 = new RedisRunner().port(6900).randomDir().nosave();
    RedisRunner slave2 = new RedisRunner().port(6901).randomDir().nosave();
    RedisRunner slave3 = new RedisRunner().port(6902).randomDir().nosave();

    ClusterRunner clusterRunner = new ClusterRunner()
            .addNode(master1, slave1)
            .addNode(master2, slave2)
            .addNode(master3, slave3);
    ClusterRunner.ClusterProcesses process = clusterRunner.run();

    Thread.sleep(5000);

    Config config = new Config();
    config.useClusterServers()
    .setLoadBalancer(new RandomLoadBalancer())
    .addNodeAddress(process.getNodes().stream().findAny().get().getRedisServerAddressAndPort());
    RedissonClient redisson = Redisson.create(config);

    RLock lock = redisson.getLock("myLock");
    lock.lock();
    assertThat(lock.isLocked()).isTrue();
    lock.unlock();
    assertThat(lock.isLocked()).isFalse();

    redisson.shutdown();
    process.shutdown();
}
 
Example #29
Source File: RedissonFairLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testForceUnlock() {
    RLock lock = redisson.getFairLock("lock");
    lock.lock();
    lock.forceUnlock();
    Assert.assertFalse(lock.isLocked());

    lock = redisson.getFairLock("lock");
    Assert.assertFalse(lock.isLocked());
}
 
Example #30
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsLocked() {
    RReadWriteLock rwlock = redisson.getReadWriteLock("lock");
    RLock lock = rwlock.readLock();
    Assert.assertFalse(lock.isLocked());
    lock.lock();
    Assert.assertTrue(lock.isLocked());
    lock.unlock();
    Assert.assertFalse(lock.isLocked());
}