導入依賴 根據(jù)springboot版本不同自行選擇版本
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson-spring-boot-starter</artifactId>
<version>3.15.3</version>
</dependency>文章來源:http://www.zghlxwxcb.cn/news/detail-805376.html
創(chuàng)建客戶端文章來源地址http://www.zghlxwxcb.cn/news/detail-805376.html
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://192.168.232.100:6379");
return Redisson
.create(config);
}
//創(chuàng)建一個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("去庫存失敗");
}
到了這里,關(guān)于運用分布式鎖 redisson的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!