案例:超卖
redis 中存储5000个商品库存,即缓存一个key为stock,值为 5000。使用jmeter 压测工具,设置5000次并发请求。要求每请求一次接口库存数量减1。
以下是redisson 实现分布式锁的代码
1. 配置Redisson
@Configuration
public class RedissonConfig {
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
config.useSingleServer()
.setAddress("redis://192.168.31.225:16379")
.setPassword("hadoop123");
return Redisson.create(config);
}
}
2. Service 层业务代码实现
public void deduct() {
RLock lock = this.redissonClient.getLock("lock");
// 加锁
lock.lock();
try {
// 查询库存信息
String stock = redisTemplate.opsForValue().get("stock");
if (stock != null && stock.length() != 0) {
int st = Integer.parseInt(stock);
if (st > 0) {
// 减库存
redisTemplate.opsForValue().set("stock", String.valueOf(--st));
}
}
} finally {
// 释放锁
lock.unlock();
}
}