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

The following examples show how to use org.redisson.api.RLock#unlock() . 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: 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 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: 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 4
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 5
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 6
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 7
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());
}
 
Example 8
Source File: InitialCodeServiceImpl.java    From short-url with Apache License 2.0 5 votes vote down vote up
@Scheduled (initialDelay = 10 * 1000, fixedDelay = 2 * 60 * 1000)
public void timedUpdateInUseInitialCodeSet() {
    initialCodeCache.refreshExpiration(initialCode);
    RLock lock = redissonClient.getLock(DISTRIBUTED_LOCK_NAME);
    try {
        if (!lock.tryLock(3, 30, TimeUnit.SECONDS)) {
            return;
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
        return;
    }

    try {
        String serverUUID = serverUUIDCache.getServerUUID();
        logger.info("server uuid {}", serverUUID);

        if (serverUUID == null) {
            serverUUIDCache.setServerUUID(uuid);
            logger.info("server uuid is null, set uuid " + uuid);
            return;
        }

        if (uuid.equals(serverUUID)) {
            logger.info("refresh server uuid and remove expired initial code");
            serverUUIDCache.refreshExpiration();
            initialCodeCache.removeExpiredInitialCode();
        }
    } finally {
        lock.unlock();
    }
}
 
Example 9
Source File: RedissonInstrumentationTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
/**
 * redisson use EVAL to implement distributed locks
 */
@Test
void testLock() {
    try (Scope scope = tracer.startRootTransaction(getClass().getClassLoader()).withName("transaction").activateInScope()) {
        RLock lock = redisson.getLock("lock");
        lock.lock();
        lock.unlock();
    }

    assertTransactionWithRedisSpans("EVAL", "EVAL");
}
 
Example 10
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 11
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 12
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 13
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 14
Source File: RedissonDistributedLock.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Override
public void unlock(Object lock) {
    if (lock != null) {
        if (lock instanceof RLock) {
            RLock rLock = (RLock)lock;
            if (rLock.isLocked()) {
                rLock.unlock();
            }
        } else {
            throw new LockException("requires RLock type");
        }
    }
}
 
Example 15
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 16
Source File: RedissLockUtil.java    From spring-boot-seckill with GNU General Public License v2.0 4 votes vote down vote up
/**
   * 释放锁
   * @param lockKey
   */
  public static void unlock(String lockKey) {
  	RLock lock = redissonClient.getLock(lockKey);
lock.unlock();
  }
 
Example 17
Source File: RedissonDistributedLocker.java    From SpringBoot2.0 with Apache License 2.0 4 votes vote down vote up
@Override
public void unlock(RLock lock) {
    lock.unlock();
}
 
Example 18
Source File: RedissonDistributedLocker.java    From dk-foundation with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void unlock(String lockKey) {
    RLock lock = redissonClient.getLock(lockKey);
    lock.unlock();
}
 
Example 19
Source File: PurchaseOrderServiceImpl.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@Transactional
    @Override
    public AssembleDetailVo joinExistsAssemble(Integer assembleId,Integer skuId,Integer count,Integer shippingId) {
        //加入已经存在的拼单
        Assemble assemble = assembleMapper.selectByPrimaryKey(assembleId);
        Objects.requireNonNull(assemble,"当前拼单不存在");
        if (assemble.getStatus()==0){
            throw new ParamException("当前拼单已经失效,无法加入当前拼单");
        }
        if (assemble.getStatus()==2){
            throw new ParamException("拼单人数已满,加入拼单失败");
        }
        checkSpellArguments(assemble.getProductId(),count);
        //使用分布式锁
        Config config = new Config();
        config.useSingleServer()
                .setAddress(RedisConstant.Redisson.REDIS_ADDRESS);
        RedissonClient redisson = Redisson.create(config);
        RLock lock = redisson.getLock(RedisConstant.Redisson.LOCK_SPELL_ORDER);
        boolean locked = false;
        try{
            log.info("尝试获取拼单锁");
            locked = lock.tryLock(10,TimeUnit.SECONDS);
            log.info("获取锁的状态:{}",locked);
            if(locked){
                User user=AuthenticationInfoUtil.getUser(userMapper,memcachedClient);
                AssembleItem assembleItem=new AssembleItem();
                assembleItem.setNickname(user.getNickname());
                assembleItem.setAvatar(user.getAvatar());
                assembleItem.setAssembleId(assembleId);
                assembleItemMapper.insert(assembleItem);
//                assemble.getAssembleItems().add(assembleItem);
                assemble.setStatus(2);//拼单完成,开始进入订单生效阶段
                assembleMapper.updateByPrimaryKeySelective(assemble);
                generateOrder(user,skuId,count,assemble,shippingId);

                //更新订单下的所有发货信息,异步操作
                this.rabbitTemplate.convertAndSend(UPDATE_ORDER_EXCHANGE,"",String.valueOf(assembleId));
                rabbitTemplate.convertAndSend(ChengfengConstant.RabbitMQ.UPDATE_ORDER_EXCHANGE,
                        "update_order_queue",String.valueOf(assembleId) , message -> {
                            message.getMessageProperties().setHeader("x-delay",5000);
                            return message;
                        });
                log.info("得到锁并且完成拼单操作");
            }
            AssembleDetailVo assembleDetailVo=new AssembleDetailVo();
            BeanUtils.copyProperties(assemble,assembleDetailVo);
            List<AssembleItem> assembleItemList=Lists.newArrayList();
            assembleDetailVo.setAssembleItemList(assembleItemList);
            assembleDetailVo.getAssembleItemList().addAll( assembleMapper.selectAssembleDetailInfoById(assembleId).getAssembleItems());
            return assembleDetailVo;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            log.info("释放锁");
            if(locked){
                lock.unlock();
            }
        }
        return null;
    }
 
Example 20
Source File: RedissonDistributedLocker.java    From lion with Apache License 2.0 2 votes vote down vote up
/**
 * 解锁
 *
 * @param lock 锁信息
 */
@Override
public void unlock(RLock lock) {
    lock.unlock();
}