标签:print cat nts tco sed read tostring 方法 时间
参考官网文档:
https://github.com/redisson/redisson
查看配置详细信息:
https://github.com/redisson/redisson/wiki/Table-of-Content
#step1
redisson知识:
一,可重用锁(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();
}
}
二、公平锁(Fair Lock)
RLock fairLock = redisson.getFairLock("anyLock");
// 最常见的使用方法
fairLock.lock();
三、公平锁(Fair Lock)
RReadWriteLock rwlock = redisson.getReadWriteLock("anyRWLock");
// 最常见的使用方法
rwlock.readLock().lock();
// 或
rwlock.writeLock().lock();
四、读写锁(
)使用使用如:
@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 "开走"; }
四、信号量(Semaphore)
关门例子:设置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 "走人"; }
标签:print cat nts tco sed read tostring 方法 时间
原文地址:https://www.cnblogs.com/pingqlin341/p/14257156.html