分布式锁
Posted z360519549
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了分布式锁相关的知识,希望对你有一定的参考价值。
一: 使用redis:
@PostMapping("/v1/getLock2") public BaseResponse getLock2(@RequestBody GxyTeacherInfoDto dto) throws Exception{ String key = "product_001"; String lockvalue = UUID.randomUUID().toString(); Boolean bool = stringRedisTemplate.opsForValue().setIfAbsent(key,lockvalue,10,TimeUnit.SECONDS); if(!bool) { System.out.println("err"); return BaseResponse.error(); } try { int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); if (stock > 0) { int realStock = stock - 1; stringRedisTemplate.opsForValue().set("stock",realStock+""); System.out.println("售卖成功,剩余" + realStock); return BaseResponse.ok(); } else { System.out.println("err2"); return BaseResponse.error(); } } finally { if(lockvalue.equals(stringRedisTemplate.opsForValue().get(key))) { stringRedisTemplate.delete(key); } } }
二: 使用Redisson:
@Bean public Redisson redisson(){ Config config = new Config(); config.useSingleServer().setAddress("redis://IP:port"); return (Redisson)Redisson.create(config); }
@PostMapping("/v1/getLock3") public BaseResponse getLock3(@RequestBody GxyTeacherInfoDto dto) throws Exception{ String lockKey = "product_001"; RLock redissonLock = redisson.getLock(lockKey); try { int stock = Integer.parseInt(stringRedisTemplate.opsForValue().get("stock")); if (stock > 0) { int realStock = stock - 1; stringRedisTemplate.opsForValue().set("stock",realStock+""); System.out.println("售卖成功,剩余" + realStock); return BaseResponse.ok(); } else { System.out.println("err2"); return BaseResponse.error(); } } finally { redissonLock.unlock(); } }
以上是关于分布式锁的主要内容,如果未能解决你的问题,请参考以下文章
JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段