二、高效的分布式锁框架redisson
一、参考文献
官方文档:https://github.com/redisson/redisson
查看配置详细信息:
https://github.com/redisson/redisson/wiki/Table-of-Content
二、redisson介绍
1.概念
Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。其中包括(BitSet, Set, Multimap, SortedSet, Map, List, Queue, BlockingQueue, Deque, BlockingDeque, Semaphore, Lock, AtomicLong, CountDownLatch, Publish / Subscribe, Bloom filter, Remote service, Spring cache, Executor service, Live Object service, Scheduler service) Redisson提供了使用Redis的最简单和最便捷的方法。Redisson的宗旨是促进使用者对Redis的关注分离(Separation of Concern),从而让使用者能够将精力更集中地放在处理业务逻辑上。
三、redisson的测试
1.可重用锁(Reentrant Lock)
RLock lock = redisson.getLock("anyLock");
// 最常见的使用方法
lock.lock();
如等待锁时间释放,或直接返回结果,不等待
// 加锁以后10秒钟自动解锁
// 无需调用unlock方法手动解锁
lock.lock(10, TimeUnit.SECONDS);
// 尝试加锁,最多等待100秒,上锁以后10秒自动解锁
boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
if (res) {
try {
...
} finally {
lock.unlock();
}
}
2.公平锁(Fair Lock)
RLock fairLock = redisson.getFairLock("anyLock");
// 最常见的使用方法
fairLock.lock();
3.读写锁(ReadWriteLock)
@GetMapping("/read") @ResponseBody public String read() { RReadWriteLock lock = redissonClient.getReadWriteLock("ReadWrite-Lock"); RLock rLock = lock.readLock(); String s = ""; try { rLock.lock(); System.out.println("读锁加锁"+Thread.currentThread().getId()); Thread.sleep(5000); s= redisTemplate.opsForValue().get("lock-value"); }finally { rLock.unlock(); return "读取完成:"+s; } } @GetMapping("/write") @ResponseBody public String write() { RReadWriteLock lock = redissonClient.getReadWriteLock("ReadWrite-Lock"); RLock wLock = lock.writeLock(); String s = UUID.randomUUID().toString(); try { wLock.lock(); System.out.println("写锁加锁"+Thread.currentThread().getId()); Thread.sleep(10000); redisTemplate.opsForValue().set("lock-value",s); } catch (InterruptedException e) { e.printStackTrace(); }finally { wLock.unlock(); return "写入完成:"+s; } }
停车场例子:信号量为存储在redis中的一个数字,当这个数字大于0时,即可以调用acquire()
方法增加数量,也可以调用release()
方法减少数量,但是当调用release()
@GetMapping("/park") @ResponseBody public String park() { RSemaphore park = redissonClient.getSemaphore("park"); try { park.acquire(5); } catch (InterruptedException e) { e.printStackTrace(); } return "停车"; } @GetMapping("/go") @ResponseBody public String go() { RSemaphore park = redissonClient.getSemaphore("park"); park.release(1); return "开走"; }
5.闭锁(DownLatch)
关门例子:设置5个人,直到所有人离开为0时,关门接口才执行完
@GetMapping("/closeDoor") @ResponseBody public String closeDoor() { RCountDownLatch latch = redissonClient.getCountDownLatch("CountDownLatch"); try { latch.trySetCount(5); latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } return "关门"; } @GetMapping("/go") @ResponseBody public String go() { RCountDownLatch latch = redissonClient.getCountDownLatch("CountDownLatch"); latch.countDown(); return "走人"; }
项目地址:https://gitee.com/pan_quan_lin/yqzj-cloud-study/tree/master/yqzj-redission