详情请参考官方文档添加链接描述
@RequestMapping("/hello") @ResponseBody public String hello(){ RLock lock = redissonClient.getLock("my-lock"); //阻塞式等待,默认等待时长30s lock.lock(); //10秒钟自动解锁,自动解锁时间一定要大于业务执行时间(不会自动续期) // lock.lock(10,TimeUnit.SECONDS); try { System.out.println("加锁成功执行业务代码....." + Thread.currentThread().getName()); Thread.sleep(30000); }catch (Exception e){ e.printStackTrace(); }finally { System.out.println("释放锁...." + Thread.currentThread().getName()); lock.unlock(); } return "hello,java小生不才"; }
@GetMapping(value = "/lockDoor") @ResponseBody public String lockDoor() throws InterruptedException { RCountDownLatch door = redissonClient.getCountDownLatch("door"); door.trySetCount(5); //等待闭锁完成 door.await(); return "我们放假了..."; } @GetMapping(value = "/goHome/{id}") @ResponseBody public String gogogo(@PathVariable("id") Long id) { RCountDownLatch door = redissonClient.getCountDownLatch("door"); //计数-1 door.countDown(); return id + "班的人都走了..."; }3.信号量
@GetMapping(value = "/park") @ResponseBody public String park() throws InterruptedException { RSemaphore park = redissonClient.getSemaphore("park"); //获取一个信号、获取一个值,占一个车位 //park.acquire(); boolean flag = park.tryAcquire(); if (flag) { //执行业务 } else { return "error"; } return "ok=>" + flag; } @GetMapping(value = "/go") @ResponseBody public String go() { RSemaphore park = redissonClient.getSemaphore("park"); //释放一个车位 park.release(); return "ok"; }4.读写锁
@GetMapping(value = "/write") @ResponseBody public String writevalue() { String s = ""; RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock"); RLock rLock = readWriteLock.writeLock(); try { //1、改数据加写锁,读数据加读锁 rLock.lock(); s = UUID.randomUUID().toString(); ValueOperations5.查询三级分类数据进一步优化ops = stringRedisTemplate.opsForValue(); ops.set("writevalue",s); TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } finally { rLock.unlock(); } return s; } @GetMapping(value = "/read") @ResponseBody public String readValue() { String s = ""; RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock"); //加读锁 RLock rLock = readWriteLock.readLock(); try { rLock.lock(); ValueOperations ops = stringRedisTemplate.opsForValue(); s = ops.get("writevalue"); try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } finally { rLock.unlock(); } return s; }
public Map> getCatalogJsonFromDbWithRedissonLock() { //1、占分布式锁。去redis占坑 //(锁的粒度,越细越快:具体缓存的是某个数据,11号商品) product-11-lock //RLock catalogJsonLock = redissonClient.getLock("catalogJson-lock"); //创建读锁 RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("catalogJson-lock"); RLock rLock = readWriteLock.readLock(); Map > dataFromDb = null; try { rLock.lock(); //加锁成功...执行业务 dataFromDb = getCatalogJsonByDB(); } finally { rLock.unlock(); } return dataFromDb; }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)