1.主要流程解读
//分布式锁
public void buy(Integer id, Integer num) {
// 1.制定锁key
String lockKey = "buy:product:" + id;
// 2.按照key获取锁实例
RLock lock = redissonClient.getLock(lockKey);
try {
//3.获取锁,如果被占用,则等待
boolean res = lock.tryLock(10, TimeUnit.SECONDS);
//4.获取锁成功,则进行业务
if (res) {
Store store = storeMapper.selectById(id);
//模拟业务处理休息50毫秒
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
store.setNum(store.getNum() - 1);
storeMapper.updateById(store);
}
} catch (Exception ex) {
System.out.println("获取锁超时!" + ex);
} finally {
// 5.释放锁
lock.unlock();
}
}
2.springboot整合过程