导入依赖 根据springboot版本不同自行选择版本
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.15.3</version>
</dependency>
创建客户端
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://192.168.232.100:6379");
return Redisson
.create(config);
}
//创建一个key 如果有这个key lock返回true 否则返回false
RLock lock = redissonClient.getLock("r_lock");
//把全部商品信息放进redis中
storeService.check();
//如果true
if (hasLock) {
try {
String maota = stringRedisTemplate.opsForValue().get("store:1");
Long maotao = Long.valueOf(maota);
if (maotao > 0) {
maotao = stringRedisTemplate.opsForValue().decrement("store:1");
log.debug("售出茅台一瓶,还剩:{}瓶", maotao);
new Thread(()->storeService.updateByBookId(1,1));
return HttpResp.success("去库存成功");
}
} finally {
//成功与否都删除key
lock.unlock();
log.debug("释放分布式锁成功");
}
}
log.debug("去库存失败");
return HttpResp.failed("去库存失败");
}