Redisson锁学习

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u013126379/article/details/79670410

1、可重入锁

public void reentrantLockTest(){
     RLock rLock = redisson.getLock("reentrantLock");
try {
     boolean tryLock = rLock.tryLock(10,TimeUnit.SECONDS);
     if(tryLock){
	//doSomething
        }
     } catch (Exception e) {
    e.printStackTrace();
   }finally{
	 rLock.unlock();
  }
2、公平锁
  public void fairLockTest(){
    RLock fairLock =  redisson.getFairLock("fairLock");
    try {
          fairLock.tryLock(5, 10, TimeUnit.SECONDS);
	  //doSomething
     } catch (InterruptedException e) {
          e.printStackTrace();
       }finally{
           fairLock.unlock();
        }
    }

3、联锁

public void multiLockTest(){
    RLock lock1 = redisson1.getLock("lock1");
    RLock lock2 = redisson2.getLock("lock2");
    RLock lock3 = redisson3.getLock("lock3");
    RedissonMultiLock lock = new RedissonMultiLock(lock1, lock2, lock3);
    try {
         lock.tryLock(5, TimeUnit.SECONDS);
           //doSomething
          } catch (InterruptedException e) {
            e.printStackTrace();
         }finally{
           lock.unlock();
          }
   }

4、红锁

public void redLockTest(){
    	RLock lock1 = redisson1.getLock("lock1");
    	RLock lock2 = redisson2.getLock("lock2");
    	RLock lock3 = redisson3.getLock("lock3");
    	RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
    	try {
	lock.tryLock(5, TimeUnit.SECONDS);
		//doSomething
	} catch (InterruptedException e) {
			e.printStackTrace();
	}finally{
		lock.unlock();
	}
    }

5、读写锁

 public void readwriteLockTest(){
    	RReadWriteLock lock = redisson.getReadWriteLock("readwriteLockTest");
    	lock.readLock().lock(10, TimeUnit.SECONDS);//10秒后自动解锁
    	//doSomething
    	//lock.writeLock().lock(5, TimeUnit.SECONDS);
    }

6、Redisson防重

    //检查分布式对象是否存在
    public Boolean  existSet(String name){
    	RLock lock = redisson.getLock("testExistAndLock");
    	try {
			boolean tryLock = lock.tryLock(10,TimeUnit.SECONDS);
			if(tryLock){
				RSet<Object> rSet = redisson.getSet(name);
				if(rSet.isExists()){
					return true;
				}				
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			lock.unlock();
		}
		return false;
    }


展开阅读全文

没有更多推荐了,返回首页