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

The following examples show how to use org.redisson.api.RLock#lock() . 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: RedisLockAspect.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Around("@annotation(redisLock)")
public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {
	String spel = redisLock.key();
	String lockName = redisLock.lockName();

	RLock rLock = redissonClient.getLock(getRedisKey(joinPoint,lockName,spel));

	rLock.lock(redisLock.expire(),redisLock.timeUnit());

	Object result = null;
	try {
		//执行方法
		result = joinPoint.proceed();

	} finally {
		rLock.unlock();
	}
	return result;
}
 
Example 2
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 6 votes vote down vote up
@Test
public void testExpire() throws InterruptedException {
    RLock lock = redisson.getLock("lock");
    lock.lock(2, TimeUnit.SECONDS);

    final long startTime = System.currentTimeMillis();
    Thread t = new Thread() {
        public void run() {
            RLock lock1 = redisson.getLock("lock");
            lock1.lock();
            long spendTime = System.currentTimeMillis() - startTime;
            Assert.assertTrue(spendTime < 2020);
            lock1.unlock();
        };
    };

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

    assertThatThrownBy(() -> {
        lock.unlock();
    }).isInstanceOf(IllegalMonitorStateException.class);
}
 
Example 3
Source File: LockExamples.java    From redisson-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
    // connects to 127.0.0.1:6379 by default
    RedissonClient redisson = Redisson.create();
    
    RLock lock = redisson.getLock("lock");
    lock.lock(2, TimeUnit.SECONDS);

    Thread t = new Thread() {
        public void run() {
            RLock lock1 = redisson.getLock("lock");
            lock1.lock();
            lock1.unlock();
        };
    };

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

    lock.unlock();
    
    redisson.shutdown();
}
 
Example 4
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 5
Source File: RedissLockDemo.java    From spring-boot-seckill with GNU General Public License v2.0 6 votes vote down vote up
/**
	 * 公平锁(Fair Lock)
	 * Redisson分布式可重入公平锁也是实现了java.util.concurrent.locks.Lock接口的一种RLock对象。
	 * 在提供了自动过期解锁功能的同时,保证了当多个Redisson客户端线程同时请求加锁时,优先分配给先发出请求的线程。
	 * @param redisson
	 */
	public void testFairLock(RedissonClient redisson){  
	    RLock fairLock = redisson.getFairLock("anyLock");  
	    try{  
	        // 最常见的使用方法  
	        fairLock.lock();  
	        // 支持过期解锁功能, 10秒钟以后自动解锁,无需调用unlock方法手动解锁  
	        fairLock.lock(10, TimeUnit.SECONDS);  
	        // 尝试加锁,最多等待100秒,上锁以后10秒自动解锁  
	        boolean res = fairLock.tryLock(100, 10, TimeUnit.SECONDS);  
	        if (res) {
				// do your business
			}
	    } catch (InterruptedException e) {  
	        e.printStackTrace();  
	    } finally {  
	        fairLock.unlock();  
	    }  
//      Redisson同时还为分布式可重入公平锁提供了异步执行的相关方法:
//	    RLock fairLock = redisson.getFairLock("anyLock");  
//	    fairLock.lockAsync();  
//	    fairLock.lockAsync(10, TimeUnit.SECONDS);  
//	    Future<Boolean> res = fairLock.tryLockAsync(100, 10, TimeUnit.SECONDS);  
	}
 
Example 6
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 7
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 8
Source File: RattingInterceptorService.java    From heimdall with Apache License 2.0 5 votes vote down vote up
/**
 * Limits the number of requests to a specific path
 *
 * @param name RLock name
 * @param path rate limit key
 */
public void execute(String name, String path, Long calls, Interval interval, Long id) {
    RequestContext ctx = RequestContext.getCurrentContext();

    RLock lock = rateLimitRepository.getLock(name);
    lock.lock();

    RateLimit rate = rateLimitRepository.find(path);

    if (rate == null) {
        rate = rateLimitRepository.mountRatelimit(id, calls, interval);
    }

    if (rate.getLastRequest() == null) {
        rate.setLastRequest(LocalDateTime.now());
    }

    if (hasIntervalEnded(rate)) {
        rate.reset();
        rate.decreaseRemaining();
        rateLimitRepository.save(rate);
    } else {
        if (rate.hasRemaining()) {
            rate.decreaseRemaining();
            rateLimitRepository.save(rate);
        } else {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.TOO_MANY_REQUESTS.value());
            ctx.setResponseBody(HttpStatus.TOO_MANY_REQUESTS.getReasonPhrase());
        }

    }
    lock.unlock();
}
 
Example 9
Source File: RedissionUtilsTest.java    From Redis_Learning with Apache License 2.0 5 votes vote down vote up
/** 
 * RLock ӳ��Ϊredis server��string ���� 
 * string�д�� �̱߳�ʾ���̼߳��� 
 * �鿴���м�---->keys * 
 * �鿴key������--->type testLock1 
 * �鿴key��ֵ ---->get testLock1  
 * �������redis server�� ���� testLock1 
 * �Ͳ���ʹ��   rLock.unlock(); 
 * ��Ϊʹ�� rLock.unlock(); ֮�� �ͻ�ɾ��redis server�е� testLock1 
 *  
 */  
@Test  
public void testGetRLock() {  
    RLock rLock=RedissionUtils.getInstance().getRLock(redisson, "testLock1");  
    if(rLock.isLocked()) rLock.unlock();  
    else rLock.lock();  
    //  
    System.out.println(rLock.getName());  
    System.out.println(rLock.getHoldCount());  
    System.out.println(rLock.isLocked());  
    rLock.unlock();  
}
 
Example 10
Source File: TracingRedissonTest.java    From java-redis-client with Apache License 2.0 5 votes vote down vote up
@Test
public void test_lock() {
  RLock lock = client.getLock("lock");

  lock.lock(10, TimeUnit.SECONDS);
  lock.unlock();

  List<MockSpan> spans = tracer.finishedSpans();
  assertEquals(2, spans.size());
  checkSpans(spans);
  assertNull(tracer.activeSpan());
}
 
Example 11
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 12
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testForceUnlock() {
    RLock lock = redisson.getLock("lock");
    lock.lock();
    lock.forceUnlock();
    Assert.assertFalse(lock.isLocked());

    lock = redisson.getLock("lock");
    Assert.assertFalse(lock.isLocked());
}
 
Example 13
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 14
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
private void testHoldCount(RLock 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 15
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 16
Source File: RedissonLockTest.java    From redisson with Apache License 2.0 5 votes vote down vote up
@Test
public void testIsHeldByCurrentThread() {
    RLock lock = redisson.getLock("lock");
    Assert.assertFalse(lock.isHeldByCurrentThread());
    lock.lock();
    Assert.assertTrue(lock.isHeldByCurrentThread());
    lock.unlock();
    Assert.assertFalse(lock.isHeldByCurrentThread());
}
 
Example 17
Source File: RedisCache.java    From gcp-token-broker with Apache License 2.0 4 votes vote down vote up
public Lock acquireLock(String lockName) {
    RLock lock = getClient().getLock(lockName);
    lock.lock();
    return lock;
}
 
Example 18
Source File: SingleRedisLock.java    From SnowJena with Apache License 2.0 4 votes vote down vote up
public void acquire(String lockName){
    String key = LOCK_TITLE + lockName;
    RLock mylock = redisson.getLock(key);
    mylock.lock(5, TimeUnit.MINUTES); //lock提供带timeout参数,timeout结束强制解锁,防止死锁
}
 
Example 19
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Test
public void testWriteLock() throws InterruptedException {
    final RReadWriteLock lock = redisson.getReadWriteLock("lock");

    final RLock writeLock = lock.writeLock();
    writeLock.lock();

    Assert.assertTrue(lock.writeLock().tryLock());

    Thread t = new Thread() {
        public void run() {
             Assert.assertFalse(writeLock.isHeldByCurrentThread());
             Assert.assertTrue(writeLock.isLocked());
             Assert.assertFalse(lock.readLock().tryLock());
             Assert.assertFalse(redisson.getReadWriteLock("lock").readLock().tryLock());

             try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

             Assert.assertTrue(lock.readLock().tryLock());
             Assert.assertTrue(redisson.getReadWriteLock("lock").readLock().tryLock());
        };
    };

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

    writeLock.unlock();
    Assert.assertTrue(lock.readLock().tryLock());
    Assert.assertTrue(writeLock.isHeldByCurrentThread());
    writeLock.unlock();
    Thread.sleep(1000);

    Assert.assertFalse(lock.writeLock().tryLock());
    Assert.assertFalse(lock.writeLock().isLocked());
    Assert.assertFalse(lock.writeLock().isHeldByCurrentThread());
    lock.writeLock().forceUnlock();
}
 
Example 20
Source File: RedissonReadWriteLockTest.java    From redisson with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiRead() throws InterruptedException {
    final RReadWriteLock lock = redisson.getReadWriteLock("lock");
    Assert.assertFalse(lock.readLock().forceUnlock());

    final RLock readLock1 = lock.readLock();
    readLock1.lock();

    Assert.assertFalse(lock.writeLock().tryLock());

    final AtomicReference<RLock> readLock2 = new AtomicReference<RLock>();
    Thread t = new Thread() {
        public void run() {
             RLock r = lock.readLock();
             Assert.assertFalse(readLock1.isHeldByCurrentThread());
             Assert.assertTrue(readLock1.isLocked());
             r.lock();
             readLock2.set(r);

             try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            r.unlock();
        };
    };

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

    Assert.assertTrue(readLock2.get().isLocked());

    readLock1.unlock();
    Assert.assertFalse(lock.writeLock().tryLock());
    Assert.assertFalse(readLock1.isHeldByCurrentThread());
    Thread.sleep(1000);

    Assert.assertFalse(readLock2.get().isLocked());
    Assert.assertTrue(lock.writeLock().tryLock());
    Assert.assertTrue(lock.writeLock().isLocked());
    Assert.assertTrue(lock.writeLock().isHeldByCurrentThread());
    lock.writeLock().unlock();

    Assert.assertFalse(lock.writeLock().isLocked());
    Assert.assertFalse(lock.writeLock().isHeldByCurrentThread());
    Assert.assertTrue(lock.writeLock().tryLock());
    lock.writeLock().forceUnlock();
}