分布式锁Redisson
2020-09-14 本文已影响0人
Lucie_xxm
概述
Redis锁都是一次性完成的工作,自己写好,后续直接使用工具类,网上已有好心人帮我们封装好直接使用就可以了,不重复造轮子
Redisson原理
imageRedisson 锁的问题
在主从结构的时候 在主节点还没来得及同步到其它redis主节点的时候挂了,可以用redlock 解决
在允许容错的情况下redis锁比较简单,但是不允许的情况下可以使用Zookeeper锁
POM依赖
springboot有整合依赖自行去查询
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.1</version>
</dependency>
代码
Application
@SpringBootApplication
@Component
public class RedisLockApplication {
public static void main(String[] args) {
SpringApplication.run(RedisLockApplication.class, args);
}
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer().setAddress("redis://localhost:6379").setPassword("123456");
// 构造RedissonClient
return Redisson.create(config);
}
}
OrderController
@RestController
@RequestMapping("/order")
@AllArgsConstructor
public class OrderController {
private OrderService orderService;
private final RedissonClient redisson;
private static ReentrantLock lock = new ReentrantLock();
private static Boolean localLock = false;
private StringRedisTemplate redisTemplate;
@GetMapping("/reduce_order")
public String executor() {
reduceOrder();
return "end";
}
public void reduceOrder() {
String productKey = "order";
RLock rlock = redisson.getLock(productKey);
try {
lock.lock();
boolean result = rlock.tryLock(1, 1, TimeUnit.SECONDS);
if (!result) { //true
System.out.println("正在抢货中.....");
return;
}
int order = Integer.parseInt(Objects.requireNonNull(redisTemplate.opsForValue().get(productKey)));
if (order > 0) {
int realorder = order - 1;
redisTemplate.opsForValue().set(productKey, String.valueOf(realorder));
System.out.println("订单数-1,剩余订单数量:" + realorder);
} else {
System.out.println("库存数不足,请及时补充订单");
}
} catch (Exception e) {
System.out.println("订单扣除失败");
e.printStackTrace();
} finally {
// System.out.println("解锁成功");
rlock.unlock();
lock.unlock();
}
}
}